text stringlengths 1 1.05M |
|---|
;
; Long Mode
;
; print.asm
;
; Since we no longer have access to BIOS utilities, this function
; takes advantage of the VGA memory area. We will go over this more
; in a subsequent chapter, but it is a sequence in memory which
; controls what is printed on the screen.
[bits 64]
; Simple 32-bit protected print routine
; Style stored in rdi, message stored in rsi
print_long:
; The pusha command stores the values of all
; registers so we don't have to worry about them
push rax
push rdx
push rdi
push rsi
mov rdx, vga_start
shl rdi, 8
; Do main loop
print_long_loop:
; If char == \0, string is done
cmp byte[rsi], 0
je print_long_done
; Handle strings that are too long
cmp rdx, vga_start + vga_extent
je print_long_done
; Move character to al, style to ah
mov rax, rdi
mov al, byte[rsi]
; Print character to vga memory location
mov word[rdx], ax
; Increment counter registers
add rsi, 1
add rdx, 2
; Redo loop
jmp print_long_loop
print_long_done:
; Popa does the opposite of pusha, and restores all of
; the registers
pop rsi
pop rdi
pop rdx
pop rax
ret |
.inesprg 1
.ineschr 1
.inesmap 0
.inesmir 1
.bank 0
.org $8000
RESET:
sei
cld
lda #%10000000
sta $2001
FOREVER:
jmp FOREVER
.bank 1
.org $FFFA
.dw 0, RESET, 0
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ime/fake_input_method.h"
#include "base/logging.h"
#include "base/string16.h"
#include "ui/base/events/event.h"
#include "ui/base/events/event_constants.h"
#include "ui/base/events/event_utils.h"
#include "ui/base/glib/glib_integers.h"
#include "ui/base/ime/input_method_delegate.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/keycodes/keyboard_code_conversion.h"
#if defined(USE_X11)
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "ui/base/keycodes/keyboard_code_conversion_x.h"
#endif
namespace {
#if defined(USE_X11)
uint32 EventFlagsFromXFlags(unsigned int flags) {
return (flags & LockMask ? ui::EF_CAPS_LOCK_DOWN : 0U) |
(flags & ControlMask ? ui::EF_CONTROL_DOWN : 0U) |
(flags & ShiftMask ? ui::EF_SHIFT_DOWN : 0U) |
(flags & Mod1Mask ? ui::EF_ALT_DOWN : 0U);
}
#endif
} // namespace
namespace ui {
FakeInputMethod::FakeInputMethod(internal::InputMethodDelegate* delegate)
: delegate_(NULL),
text_input_client_(NULL) {
SetDelegate(delegate);
}
FakeInputMethod::~FakeInputMethod() {
}
void FakeInputMethod::SetDelegate(internal::InputMethodDelegate* delegate) {
delegate_ = delegate;
}
void FakeInputMethod::SetFocusedTextInputClient(TextInputClient* client) {
text_input_client_ = client;
}
TextInputClient* FakeInputMethod::GetTextInputClient() const {
return text_input_client_;
}
void FakeInputMethod::DispatchKeyEvent(const base::NativeEvent& native_event) {
#if defined(OS_WIN)
if (native_event.message == WM_CHAR) {
if (text_input_client_) {
text_input_client_->InsertChar(ui::KeyboardCodeFromNative(native_event),
ui::EventFlagsFromNative(native_event));
}
} else {
delegate_->DispatchKeyEventPostIME(native_event);
}
#elif defined(USE_X11)
DCHECK(native_event);
if (native_event->type == KeyRelease) {
// On key release, just dispatch it.
delegate_->DispatchKeyEventPostIME(native_event);
} else {
const uint32 state = EventFlagsFromXFlags(native_event->xkey.state);
// Send a RawKeyDown event first,
delegate_->DispatchKeyEventPostIME(native_event);
if (text_input_client_) {
// then send a Char event via ui::TextInputClient.
const KeyboardCode key_code = ui::KeyboardCodeFromNative(native_event);
uint16 ch = 0;
if (!(state & ui::EF_CONTROL_DOWN))
ch = ui::GetCharacterFromXEvent(native_event);
if (!ch)
ch = ui::GetCharacterFromKeyCode(key_code, state);
if (ch)
text_input_client_->InsertChar(ch, state);
}
}
#else
// TODO(yusukes): Support other platforms. Call InsertChar() when necessary.
delegate_->DispatchKeyEventPostIME(native_event);
#endif
}
void FakeInputMethod::Init(bool focused) {}
void FakeInputMethod::OnFocus() {}
void FakeInputMethod::OnBlur() {}
void FakeInputMethod::OnTextInputTypeChanged(const TextInputClient* client) {}
void FakeInputMethod::OnCaretBoundsChanged(const TextInputClient* client) {}
void FakeInputMethod::CancelComposition(const TextInputClient* client) {}
std::string FakeInputMethod::GetInputLocale() {
return "";
}
base::i18n::TextDirection FakeInputMethod::GetInputTextDirection() {
return base::i18n::UNKNOWN_DIRECTION;
}
bool FakeInputMethod::IsActive() {
return true;
}
ui::TextInputType FakeInputMethod::GetTextInputType() const {
return ui::TEXT_INPUT_TYPE_NONE;
}
bool FakeInputMethod::CanComposeInline() const {
return true;
}
} // namespace ui
|
device ZXSPECTRUMNEXT
BORDER: equ $c350
Start: equ $8000
org Start
jr SetupISR
Update:
ld a,(BORDER)
break
inc a
ld c,7
and c
out (254),a
ld (BORDER),a
ret
SetupISR:
; Setup the 128 entry vector table
di
ld hl, IM2Table
ld de, IM2Table+1
ld bc, 256
; Setup the I register (the high byte of the table)
ld a, h
ld i, a
; Set the first entries in the table to $FC
ld a, $FC
ld (hl), a
; Copy to all the remaining 256 bytes
ldir
; Setup IM2 mode
im 2
ei
ret
ORG $FCFC
; ISR (Interrupt Service Routine)
ISR:
push af
push hl
push bc
push de
push ix
push iy
exx
ex af, af'
push af
push hl
push bc
push de
call Update
pop de
pop bc
pop hl
pop af
ex af, af'
exx
pop iy
pop ix
pop de
pop bc
pop hl
pop af
ei
rst $18:DW $0038
; Make sure this is on a 256 byte boundary
ORG $FE00
IM2Table:
defs 257
;SAVESNA "i3.sna", Start
SAVENEX OPEN "i3.nex", Start, $ff40
SAVENEX CORE 3, 0, 0 ; core 3.0.0 required
SAVENEX CFG 1 ; blue border (as debug)
SAVENEX AUTO ; dump all modified banks into NEX file |
.size 8000
.text@48
ld a, ff
ldff(45), a
jp lstatint
.text@100
jp lbegin
.text@150
lbegin:
ld a, ff
ldff(45), a
ld b, 03
call lwaitly_b
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
ei
ld a, b
inc a
inc a
ldff(45), a
ld c, 41
.text@1000
lstatint:
xor a, a
ldff(c), a
ldff(0f), a
.text@1060
ldff(c), a
ldff a, (0f)
and a, b
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
; --------------------------------------
; Test ADD, and moving data from addresses to registers and back.
;
; 8085 program to add two 8 bit numbers
; https://www.geeksforgeeks.org/assembly-language-program-8085-microprocessor-add-two-8-bit-numbers/
;
; --------------------------------------
jmp Start ; Jump to start of the test program.
;
Halt:
hlt ; The program will halt at each iteration, after the first.
; --------------------------------------
Start:
LDA 2050 ; A<-[2050]
MOV H, A ; H<-A
LDA 2051 ; A<-[2051]
ADD H ; A<-A+H
MOV L, A ; L<-A
MVI A,0 ; A<-0
ADC A ; A<-A+A+carry
MOV H, A ; H<-A
SHLD 3050 ; H->3051, L->3050
; --------------------------------------
; --------------------------------------
jmp Halt ; Jump back to the early halt command.
; --------------------------------------
end |
; A211666: Number of iterations log_10(log_10(log_10(...(n)...))) such that the result is < 2.
; 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2
lpb $0
add $0,1
div $0,100
add $1,2
lpe
div $1,2
|
//============================================================
//
// Type: CppIntroduction implementation file
//
// Author: Tommaso Bellosta on 24/09/2019.
// Dipartimento di Scienze e Tecnologie Aerospaziali
// Politecnico di Milano
// Via La Masa 34, 20156 Milano, ITALY
// e-mail: tommaso.bellosta@polimi.it
//
// Copyright: 2019, Tommaso Bellosta and the CppIntroduction contributors.
// This software is distributed under the MIT license, see LICENSE.txt
//
//============================================================
#include <cmath>
#include <iostream>
#include "FiniteDifferenceClass.h"
//FiniteDifferenceClass::FiniteDifferenceClass(Grid* meshPtr){
//
// this->mesh = meshPtr;
//
//}
FiniteDifferenceClass::FiniteDifferenceClass() {
this->mesh = nullptr;
}
void FiniteDifferenceClass::assignGridPointer(Grid *mesh) {
this->mesh = mesh;
}
//=================== CenteredFiniteDifferenceClass ===============
double CenteredFiniteDifferenceClass::computeDerivative(int index, double(*fun)(double)){
double x_ip1;
double x_im1;
double h;
double out;
if(index == 0){
x_ip1 = this->mesh->nodes[index + 1];
h = this->mesh->getCellSize(index);
x_im1 = this->mesh->nodes[index] - h;
}
else if(index == this->mesh->nodes.size() - 1){
x_im1 = this->mesh->nodes[index - 1];
h = this->mesh->getCellSize(index - 1);
x_ip1 = this->mesh->nodes[index] + h;
}
else {
x_ip1 = this->mesh->nodes[index + 1];
x_im1 = this->mesh->nodes[index - 1];
h = this->mesh->getCellSize(index);
}
out = (fun(x_ip1) - fun(x_im1)) / (2 * h);
return out;
}
CenteredFiniteDifferenceClass::CenteredFiniteDifferenceClass(Grid *mesh){
this->mesh = mesh;
}
//=================== ForwardFiniteDifferenceClass ===============
ForwardFiniteDifferenceClass::ForwardFiniteDifferenceClass(Grid *mesh){
this->mesh = mesh;
}
double ForwardFiniteDifferenceClass::computeDerivative(int index, double(*fun)(double)){
double x_ip1;
double x_i;
double h;
if(index == this->mesh->nodes.size() - 1){
x_i = this->mesh->nodes[index];
x_ip1 = this->mesh->nodes[index] + this->mesh->getCellSize(index - 1);
h = this->mesh->getCellSize(index - 1);
}
else {
x_ip1 = this->mesh->nodes[index + 1];
x_i = this->mesh->nodes[index];
h = this->mesh->getCellSize(index);
}
double out = (fun(x_ip1) - fun(x_i)) / h;
return out;
}
//=================== FDSolver ===============
FDSolver::FDSolver(FDType finiteDiffType) {
this->setFDType(finiteDiffType);
}
void FDSolver::setFDType(FDType type) {
switch (type){
case FDType::FORWARD :
this->numericalMethod = new ForwardFiniteDifferenceClass;
break;
case FDType::CENTERED :
this->numericalMethod = new CenteredFiniteDifferenceClass;
break;
default :
// print warning
this->numericalMethod = nullptr;
}
}
FDSolver::FDSolver() {
this->numericalMethod = nullptr;
}
FDSolver::~FDSolver() {
delete this->numericalMethod;
}
std::vector<double> FDSolver::computeDerivative(Grid &grid, double (*fun)(double)) {
std::vector<double> derivative(grid.nodes.size());
this->numericalMethod->assignGridPointer(&grid);
for (int i = 0; i < grid.nodes.size(); ++i) {
derivative[i] = this->numericalMethod->computeDerivative(i, fun);
}
return derivative;
}
double
FDSolver::computeL2Norm(const std::vector<double> &numericalDeriv, Grid &grid, double (*fun)(double)) {
double L2 = 0;
double dx = grid.getCellSize(0);
double exactDerivative;
for (int i = 0; i < numericalDeriv.size(); ++i) {
exactDerivative = fun(grid.nodes[i]);
L2 += (numericalDeriv[i] - exactDerivative) * (numericalDeriv[i] - exactDerivative) * dx;
}
L2 = sqrt(L2);
return L2;
}
|
; THIS IS AN AUTOGENERATED FILE
; WARNING: FOR MACOS ONLY
; nasm -f macho64 gen_rc4.asm -o gen_rc4.o && ld -o gen_rc4.macho -macosx_version_min 10.7 -e start gen_rc4.o && ./gen_rc4.macho
BITS 64
section .text
global start
start:
push rbp
mov rbp, rsp
; PRINT OUTPUT
push 0xa203a
mov DWORD [rsp+0x4],0x0
push 0x76207965
mov DWORD [rsp+0x4],0x65756c61
push 0x7475706e
mov DWORD [rsp+0x4],0x6b206120
push 0x61656c50
mov DWORD [rsp+0x4],0x69206573
mov rax,0x2000004
mov rdi,0x1
mov rsi,rsp
mov edx,0x1b
syscall
pop rax
pop rax
pop rax
pop rax
; GET INPUT
mov rax, 0x2000003
mov rdi, 0
lea rsi, [rel key]
mov edx, 0x10
syscall
; CHECK 4 BYTES OF KEY
mov rdx, QWORD [rel key]
shr rdx, 32
cmp edx, 0x36395477
jne fail
; GENERATE SBOX
lea rcx, [rel key] ; key: rcx
mov rdx, strict qword 8 ; L: rdx
lea r8, [rel sbox] ; sbox: r8
call rc4init
lea rcx, [rel encrypted] ; bufin
mov rdx, strict qword 48 ; len
lea r8, [rel encrypted] ; bufout
lea r9, [rel sbox] ; sbox
call rc4run
mov eax, 0x2000004 ; write
mov rdi, 1 ; std out
lea rsi, [rel encrypted]
add rsi, 8
mov edx, 40
syscall
mov rax, qword [rel encrypted]
xor rbx, rbx
xor rcx, rcx
xor rdx, rdx
xor rdi, rdi
pop rbp
ret
; PRINT FAIL WHALE
fail:
mov eax, 0x2000004 ; write
mov rdi, 1 ; std out
lea rsi, [rel msg2]
mov edx, 230
syscall
xor eax, eax
mov rax, 0x2000001 ; exit
mov rdi, 0
syscall
rc4init:
push rbp
mov rbp, rsp
xor rax, rax
mov r11, 0x20
mov r9, 0x808080808080808
mov r10, 0x706050403020100
loop1_s:
cmp rax,r11
je loop1_e
mov QWORD [r8+rax*8], r10
add r10, r9
inc rax
jmp loop1_s
loop1_e:
xor rax,rax
xor r9,r9
xor r10,r10
loop2_s:
movzx r11, BYTE [r8+rax*1]
add r9, r11
movq xmm0,r11
movzx r11,BYTE [rcx+r10*1]
add r9, r11
xor r11, r11
mov r11b, r9b
xchg r9, r11
movzx r11, BYTE [r8+r9*1]
mov BYTE [r8+rax*1], r11b
movq r11, xmm0
mov BYTE [r8+r9*1], r11b
inc r10
xor r11, r11
cmp rdx, r10
cmove r10, r11
inc rax
test al, al
jne loop2_s
pop rbp
ret
rc4run:
push rbp
mov rbp, rsp
xor rax, rax
xor r10, r10
movq xmm0, r10
movq xmm1, r10
rc4run_loop1_s:
cmp rdx, rax
je rc4run_loop1_e
movq r10, xmm0
inc r10
xor r11, r11
mov r11b, r10b
movq xmm0, r11
movzx r10, BYTE [r9+r11*1]
movq r11, xmm1
movq xmm2, r10
add r10, r11
xor r11, r11
mov r11b, r10b
movq xmm1, r11
movzx r10, BYTE [r9+r11*1]
movq xmm3, r10
movq r11, xmm0
mov BYTE [r9+r11*1], r10b
movq r11, xmm1
movq r10, xmm2
mov BYTE [r9+r11*1], r10b
movq r11, xmm3
add r10, r11
xor r11, r11
mov r11b, r10b
movzx r10, BYTE [r9+r11*1]
movzx r11, BYTE [rcx+rax*1]
xor r10, r11
mov BYTE [r8+rax*1],r10b
inc rax
jmp rc4run_loop1_s
rc4run_loop1_e:
pop rbp
ret
section .data
encrypted:
db 246,44,114,26,3,153,14,120,189,144,233,104,208,105,55,41,248,18,244,229,208,251,243,126,114,97,121,25,237,68,18,82,245,249,170,20,54,13,31,178,82,107,242,106,218,157,236,60
key: times 0x10 db 0
sbox: times 0x100 db 0
msg2:
db 32,32,32,32,32,70,65,73,76,32,87,72,65,76,69,33,10,10,87,32,32,32,32,32,87,32,32,32,32,32,32,87,32,32,32,32,32,32,32,32,10,87,32,32,32,32,32,32,32,32,87,32,32,87,32,32,32,32,32,87,32,32,32,32,10,32,32,32,32,32,32,32,32,32,32,32,32,32,32,39,46,32,32,87,32,32,32,32,32,32,10,32,32,46,45,34,34,45,46,95,32,32,32,32,32,92,32,92,46,45,45,124,32,32,10,32,47,32,32,32,32,32,32,32,34,45,46,46,95,95,41,32,46,45,39,32,32,32,10,124,32,32,32,32,32,95,32,32,32,32,32,32,32,32,32,47,32,32,32,32,32,32,10,92,39,45,46,95,95,44,32,32,32,46,95,95,46,44,39,32,32,32,32,32,32,32,10,32,96,39,45,45,45,45,39,46,95,92,45,45,39,32,32,32,32,32,32,10,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,10
|
SECTION code_clib
SECTION code_fp_math48
PUBLIC _llround
EXTERN cm48_sdcciy_llround
defc _llround = cm48_sdcciy_llround
|
;--------------------------------------------------------
; File Created by SDCC : free open source ANSI-C Compiler
; Version 3.9.1 #11310 (Linux)
;--------------------------------------------------------
; Processed by Z88DK
;--------------------------------------------------------
EXTERN __divschar
EXTERN __divschar_callee
EXTERN __divsint
EXTERN __divsint_callee
EXTERN __divslong
EXTERN __divslong_callee
EXTERN __divslonglong
EXTERN __divslonglong_callee
EXTERN __divsuchar
EXTERN __divsuchar_callee
EXTERN __divuchar
EXTERN __divuchar_callee
EXTERN __divuint
EXTERN __divuint_callee
EXTERN __divulong
EXTERN __divulong_callee
EXTERN __divulonglong
EXTERN __divulonglong_callee
EXTERN __divuschar
EXTERN __divuschar_callee
EXTERN __modschar
EXTERN __modschar_callee
EXTERN __modsint
EXTERN __modsint_callee
EXTERN __modslong
EXTERN __modslong_callee
EXTERN __modslonglong
EXTERN __modslonglong_callee
EXTERN __modsuchar
EXTERN __modsuchar_callee
EXTERN __moduchar
EXTERN __moduchar_callee
EXTERN __moduint
EXTERN __moduint_callee
EXTERN __modulong
EXTERN __modulong_callee
EXTERN __modulonglong
EXTERN __modulonglong_callee
EXTERN __moduschar
EXTERN __moduschar_callee
EXTERN __mulint
EXTERN __mulint_callee
EXTERN __mullong
EXTERN __mullong_callee
EXTERN __mullonglong
EXTERN __mullonglong_callee
EXTERN __mulschar
EXTERN __mulschar_callee
EXTERN __mulsuchar
EXTERN __mulsuchar_callee
EXTERN __muluschar
EXTERN __muluschar_callee
EXTERN __rlslonglong
EXTERN __rlslonglong_callee
EXTERN __rlulonglong
EXTERN __rlulonglong_callee
EXTERN __rrslonglong
EXTERN __rrslonglong_callee
EXTERN __rrulonglong
EXTERN __rrulonglong_callee
EXTERN ___sdcc_call_hl
EXTERN ___sdcc_call_iy
EXTERN ___sdcc_enter_ix
EXTERN _banked_call
EXTERN _banked_ret
EXTERN ___fs2schar
EXTERN ___fs2schar_callee
EXTERN ___fs2sint
EXTERN ___fs2sint_callee
EXTERN ___fs2slong
EXTERN ___fs2slong_callee
EXTERN ___fs2slonglong
EXTERN ___fs2slonglong_callee
EXTERN ___fs2uchar
EXTERN ___fs2uchar_callee
EXTERN ___fs2uint
EXTERN ___fs2uint_callee
EXTERN ___fs2ulong
EXTERN ___fs2ulong_callee
EXTERN ___fs2ulonglong
EXTERN ___fs2ulonglong_callee
EXTERN ___fsadd
EXTERN ___fsadd_callee
EXTERN ___fsdiv
EXTERN ___fsdiv_callee
EXTERN ___fseq
EXTERN ___fseq_callee
EXTERN ___fsgt
EXTERN ___fsgt_callee
EXTERN ___fslt
EXTERN ___fslt_callee
EXTERN ___fsmul
EXTERN ___fsmul_callee
EXTERN ___fsneq
EXTERN ___fsneq_callee
EXTERN ___fssub
EXTERN ___fssub_callee
EXTERN ___schar2fs
EXTERN ___schar2fs_callee
EXTERN ___sint2fs
EXTERN ___sint2fs_callee
EXTERN ___slong2fs
EXTERN ___slong2fs_callee
EXTERN ___slonglong2fs
EXTERN ___slonglong2fs_callee
EXTERN ___uchar2fs
EXTERN ___uchar2fs_callee
EXTERN ___uint2fs
EXTERN ___uint2fs_callee
EXTERN ___ulong2fs
EXTERN ___ulong2fs_callee
EXTERN ___ulonglong2fs
EXTERN ___ulonglong2fs_callee
EXTERN ____sdcc_2_copy_src_mhl_dst_deix
EXTERN ____sdcc_2_copy_src_mhl_dst_bcix
EXTERN ____sdcc_4_copy_src_mhl_dst_deix
EXTERN ____sdcc_4_copy_src_mhl_dst_bcix
EXTERN ____sdcc_4_copy_src_mhl_dst_mbc
EXTERN ____sdcc_4_ldi_nosave_bc
EXTERN ____sdcc_4_ldi_save_bc
EXTERN ____sdcc_4_push_hlix
EXTERN ____sdcc_4_push_mhl
EXTERN ____sdcc_lib_setmem_hl
EXTERN ____sdcc_ll_add_de_bc_hl
EXTERN ____sdcc_ll_add_de_bc_hlix
EXTERN ____sdcc_ll_add_de_hlix_bc
EXTERN ____sdcc_ll_add_de_hlix_bcix
EXTERN ____sdcc_ll_add_deix_bc_hl
EXTERN ____sdcc_ll_add_deix_hlix
EXTERN ____sdcc_ll_add_hlix_bc_deix
EXTERN ____sdcc_ll_add_hlix_deix_bc
EXTERN ____sdcc_ll_add_hlix_deix_bcix
EXTERN ____sdcc_ll_asr_hlix_a
EXTERN ____sdcc_ll_asr_mbc_a
EXTERN ____sdcc_ll_copy_src_de_dst_hlix
EXTERN ____sdcc_ll_copy_src_de_dst_hlsp
EXTERN ____sdcc_ll_copy_src_deix_dst_hl
EXTERN ____sdcc_ll_copy_src_deix_dst_hlix
EXTERN ____sdcc_ll_copy_src_deixm_dst_hlsp
EXTERN ____sdcc_ll_copy_src_desp_dst_hlsp
EXTERN ____sdcc_ll_copy_src_hl_dst_de
EXTERN ____sdcc_ll_copy_src_hlsp_dst_de
EXTERN ____sdcc_ll_copy_src_hlsp_dst_deixm
EXTERN ____sdcc_ll_lsl_hlix_a
EXTERN ____sdcc_ll_lsl_mbc_a
EXTERN ____sdcc_ll_lsr_hlix_a
EXTERN ____sdcc_ll_lsr_mbc_a
EXTERN ____sdcc_ll_push_hlix
EXTERN ____sdcc_ll_push_mhl
EXTERN ____sdcc_ll_sub_de_bc_hl
EXTERN ____sdcc_ll_sub_de_bc_hlix
EXTERN ____sdcc_ll_sub_de_hlix_bc
EXTERN ____sdcc_ll_sub_de_hlix_bcix
EXTERN ____sdcc_ll_sub_deix_bc_hl
EXTERN ____sdcc_ll_sub_deix_hlix
EXTERN ____sdcc_ll_sub_hlix_bc_deix
EXTERN ____sdcc_ll_sub_hlix_deix_bc
EXTERN ____sdcc_ll_sub_hlix_deix_bcix
EXTERN ____sdcc_load_debc_deix
EXTERN ____sdcc_load_dehl_deix
EXTERN ____sdcc_load_debc_mhl
EXTERN ____sdcc_load_hlde_mhl
EXTERN ____sdcc_store_dehl_bcix
EXTERN ____sdcc_store_debc_hlix
EXTERN ____sdcc_store_debc_mhl
EXTERN ____sdcc_cpu_pop_ei
EXTERN ____sdcc_cpu_pop_ei_jp
EXTERN ____sdcc_cpu_push_di
EXTERN ____sdcc_outi
EXTERN ____sdcc_outi_128
EXTERN ____sdcc_outi_256
EXTERN ____sdcc_ldi
EXTERN ____sdcc_ldi_128
EXTERN ____sdcc_ldi_256
EXTERN ____sdcc_4_copy_srcd_hlix_dst_deix
EXTERN ____sdcc_4_and_src_mbc_mhl_dst_deix
EXTERN ____sdcc_4_or_src_mbc_mhl_dst_deix
EXTERN ____sdcc_4_xor_src_mbc_mhl_dst_deix
EXTERN ____sdcc_4_or_src_dehl_dst_bcix
EXTERN ____sdcc_4_xor_src_dehl_dst_bcix
EXTERN ____sdcc_4_and_src_dehl_dst_bcix
EXTERN ____sdcc_4_xor_src_mbc_mhl_dst_debc
EXTERN ____sdcc_4_or_src_mbc_mhl_dst_debc
EXTERN ____sdcc_4_and_src_mbc_mhl_dst_debc
EXTERN ____sdcc_4_cpl_src_mhl_dst_debc
EXTERN ____sdcc_4_xor_src_debc_mhl_dst_debc
EXTERN ____sdcc_4_or_src_debc_mhl_dst_debc
EXTERN ____sdcc_4_and_src_debc_mhl_dst_debc
EXTERN ____sdcc_4_and_src_debc_hlix_dst_debc
EXTERN ____sdcc_4_or_src_debc_hlix_dst_debc
EXTERN ____sdcc_4_xor_src_debc_hlix_dst_debc
;--------------------------------------------------------
; Public variables in this module
;--------------------------------------------------------
GLOBAL _m32_tanhf
;--------------------------------------------------------
; Externals used
;--------------------------------------------------------
GLOBAL _m32_polyf
GLOBAL _m32_hypotf
GLOBAL _m32_ldexpf
GLOBAL _m32_frexpf
GLOBAL _m32_invsqrtf
GLOBAL _m32_sqrtf
GLOBAL _m32_invf
GLOBAL _m32_sqrf
GLOBAL _m32_div2f
GLOBAL _m32_mul2f
GLOBAL _m32_modff
GLOBAL _m32_fmodf
GLOBAL _m32_roundf
GLOBAL _m32_floorf
GLOBAL _m32_fabsf
GLOBAL _m32_ceilf
GLOBAL _m32_powf
GLOBAL _m32_log10f
GLOBAL _m32_log2f
GLOBAL _m32_logf
GLOBAL _m32_exp10f
GLOBAL _m32_exp2f
GLOBAL _m32_expf
GLOBAL _m32_atanhf
GLOBAL _m32_acoshf
GLOBAL _m32_asinhf
GLOBAL _m32_coshf
GLOBAL _m32_sinhf
GLOBAL _m32_atan2f
GLOBAL _m32_atanf
GLOBAL _m32_acosf
GLOBAL _m32_asinf
GLOBAL _m32_tanf
GLOBAL _m32_cosf
GLOBAL _m32_sinf
GLOBAL __MAX_OPEN
;--------------------------------------------------------
; special function registers
;--------------------------------------------------------
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
SECTION bss_compiler
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
IF 0
; .area _INITIALIZED removed by z88dk
ENDIF
;--------------------------------------------------------
; absolute external ram data
;--------------------------------------------------------
SECTION IGNORE
;--------------------------------------------------------
; global & static initialisations
;--------------------------------------------------------
SECTION code_crt_init
;--------------------------------------------------------
; Home
;--------------------------------------------------------
SECTION IGNORE
;--------------------------------------------------------
; code
;--------------------------------------------------------
SECTION code_compiler
; ---------------------------------
; Function m32_tanhf
; ---------------------------------
_m32_tanhf:
push ix
ld ix,0
add ix,sp
push af
push af
push af
push af
call _m32_expf
push hl
ld c,l
ld b,h
push de
ld l, c
ld h, b
call _m32_invf
ld (ix-4),l
ld (ix-3),h
ld (ix-2),e
ld (ix-1),d
pop de
pop bc
push bc
push de
ld l,(ix-2)
ld h,(ix-1)
push hl
ld l,(ix-4)
ld h,(ix-3)
push hl
push de
push bc
call ___fssub_callee
ld (ix-8),l
ld (ix-7),h
ld (ix-6),e
ld (ix-5),d
pop de
pop bc
push bc
push de
ld l, c
ld h, b
call _m32_invf
ld (ix-4),l
ld (ix-3),h
ld (ix-2),e
ld (ix-1),d
pop de
pop bc
ld l,(ix-2)
ld h,(ix-1)
push hl
ld l,(ix-4)
ld h,(ix-3)
push hl
push de
push bc
call ___fsadd_callee
push de
push hl
ld l,(ix-6)
ld h,(ix-5)
push hl
ld l,(ix-8)
ld h,(ix-7)
push hl
call ___fsdiv
ld sp,ix
pop ix
ret
SECTION IGNORE
|
ORIGIN 4x0000
SEGMENT CodeSegment:
LEA R0, VALUE1
; R0 should contain the value 4x0012
ENDLOOP:
BRnzp ENDLOOP
NOP
NOP
NOP
NOP
NOP
NOP
NOP
SEGMENT
DATA:
VALUE1: DATA2 4x0000
|
; A108171: Tribonacci version of A076662 using beta positive real Pisot root of x^3 - x^2 - x - 1.
; 4,3,4,3,3,4,3,4,3,3,4,3,3,4,3,4,3,3,4,3,4,3,3,4,3,3,4,3,4,3,3,4,3,4,3,3,4,3,3,4,3,4,3,3,4,3,3,4,3,4,3,3,4,3,4,3,3,4,3,3,4,3,4,3,3,4,3,4,3,3,4,3,3,4,3,4,3,3,4,3,4,3,3,4,3,3,4,3,4,3,3,4,3,3,4,3,4,3,3
mov $5,$0
mov $7,2
lpb $7,1
mov $0,$5
sub $7,1
add $0,$7
mov $4,$0
mul $0,2
lpb $0,1
sub $0,1
add $4,4
lpe
mov $3,2
mul $4,2
mov $2,$4
sub $2,1
div $2,47
add $3,$4
div $3,2
add $3,$2
mov $6,$3
mov $8,$7
lpb $8,1
mov $1,$6
sub $8,1
lpe
lpe
lpb $5,1
sub $1,$6
mov $5,0
lpe
sub $1,6
|
@Assembly code to print numbers from 2 to 20
.main:
addi x1, x0, 1
addi x2, x0, 1
addi x4, x0, 20
loop:
add x3, x1, x2
.print x3
addi x2, x2, 1
bne x2, x4, loop
end |
#include once <stackf.asm>
SQRT: ; Computes SQRT(x) using ROM FP-CALC
call __FPSTACK_PUSH
rst 28h ; ROM CALC
defb 28h ; SQRT
defb 38h ; END CALC
jp __FPSTACK_POP
|
; void *_falloc_(void *p, size_t size)
INCLUDE "clib_cfg.asm"
SECTION code_alloc_malloc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_MULTITHREAD & $01
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PUBLIC _falloc_
EXTERN asm__falloc
_falloc_:
pop af
pop hl
pop bc
push bc
push hl
push af
jp asm__falloc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ELSE
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PUBLIC _falloc_
EXTERN _falloc__unlocked
defc _falloc_ = _falloc__unlocked
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/invalidation/impl/unacked_invalidation_set.h"
#include <stddef.h>
#include <memory>
#include "base/json/json_string_value_serializer.h"
#include "base/strings/string_number_conversions.h"
#include "components/invalidation/impl/unacked_invalidation_set_test_util.h"
#include "components/invalidation/public/object_id_invalidation_map.h"
#include "components/invalidation/public/single_object_invalidation_set.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer {
class UnackedInvalidationSetTest : public testing::Test {
public:
UnackedInvalidationSetTest()
: kObjectId_(10, "ASDF"),
unacked_invalidations_(kObjectId_) {}
SingleObjectInvalidationSet GetStoredInvalidations() {
ObjectIdInvalidationMap map;
unacked_invalidations_.ExportInvalidations(
base::WeakPtr<AckHandler>(),
scoped_refptr<base::SingleThreadTaskRunner>(),
&map);
ObjectIdSet ids = map.GetObjectIds();
if (ids.find(kObjectId_) != ids.end()) {
return map.ForObject(kObjectId_);
} else {
return SingleObjectInvalidationSet();
}
}
const invalidation::ObjectId kObjectId_;
UnackedInvalidationSet unacked_invalidations_;
};
namespace {
// Test storage and retrieval of zero invalidations.
TEST_F(UnackedInvalidationSetTest, Empty) {
EXPECT_EQ(0U, GetStoredInvalidations().GetSize());
}
// Test storage and retrieval of a single invalidation.
TEST_F(UnackedInvalidationSetTest, OneInvalidation) {
Invalidation inv1 = Invalidation::Init(kObjectId_, 10, "payload");
unacked_invalidations_.Add(inv1);
SingleObjectInvalidationSet set = GetStoredInvalidations();
ASSERT_EQ(1U, set.GetSize());
EXPECT_FALSE(set.StartsWithUnknownVersion());
}
// Test that calling Clear() returns us to the empty state.
TEST_F(UnackedInvalidationSetTest, Clear) {
Invalidation inv1 = Invalidation::Init(kObjectId_, 10, "payload");
unacked_invalidations_.Add(inv1);
unacked_invalidations_.Clear();
EXPECT_EQ(0U, GetStoredInvalidations().GetSize());
}
// Test that repeated unknown version invalidations are squashed together.
TEST_F(UnackedInvalidationSetTest, UnknownVersions) {
Invalidation inv1 = Invalidation::Init(kObjectId_, 10, "payload");
Invalidation inv2 = Invalidation::InitUnknownVersion(kObjectId_);
Invalidation inv3 = Invalidation::InitUnknownVersion(kObjectId_);
unacked_invalidations_.Add(inv1);
unacked_invalidations_.Add(inv2);
unacked_invalidations_.Add(inv3);
SingleObjectInvalidationSet set = GetStoredInvalidations();
ASSERT_EQ(2U, set.GetSize());
EXPECT_TRUE(set.StartsWithUnknownVersion());
}
// Tests that no truncation occurs while we're under the limit.
TEST_F(UnackedInvalidationSetTest, NoTruncation) {
size_t kMax = UnackedInvalidationSet::kMaxBufferedInvalidations;
for (size_t i = 0; i < kMax; ++i) {
Invalidation inv = Invalidation::Init(kObjectId_, i, "payload");
unacked_invalidations_.Add(inv);
}
SingleObjectInvalidationSet set = GetStoredInvalidations();
ASSERT_EQ(kMax, set.GetSize());
EXPECT_FALSE(set.StartsWithUnknownVersion());
EXPECT_EQ(0, set.begin()->version());
EXPECT_EQ(kMax-1, static_cast<size_t>(set.rbegin()->version()));
}
// Test that truncation happens as we reach the limit.
TEST_F(UnackedInvalidationSetTest, Truncation) {
size_t kMax = UnackedInvalidationSet::kMaxBufferedInvalidations;
for (size_t i = 0; i < kMax + 1; ++i) {
Invalidation inv = Invalidation::Init(kObjectId_, i, "payload");
unacked_invalidations_.Add(inv);
}
SingleObjectInvalidationSet set = GetStoredInvalidations();
ASSERT_EQ(kMax, set.GetSize());
EXPECT_TRUE(set.StartsWithUnknownVersion());
EXPECT_TRUE(set.begin()->is_unknown_version());
EXPECT_EQ(kMax, static_cast<size_t>(set.rbegin()->version()));
}
// Test that we don't truncate while a handler is registered.
TEST_F(UnackedInvalidationSetTest, RegistrationAndTruncation) {
unacked_invalidations_.SetHandlerIsRegistered();
size_t kMax = UnackedInvalidationSet::kMaxBufferedInvalidations;
for (size_t i = 0; i < kMax + 1; ++i) {
Invalidation inv = Invalidation::Init(kObjectId_, i, "payload");
unacked_invalidations_.Add(inv);
}
SingleObjectInvalidationSet set = GetStoredInvalidations();
ASSERT_EQ(kMax+1, set.GetSize());
EXPECT_FALSE(set.StartsWithUnknownVersion());
EXPECT_EQ(0, set.begin()->version());
EXPECT_EQ(kMax, static_cast<size_t>(set.rbegin()->version()));
// Unregistering should re-enable truncation.
unacked_invalidations_.SetHandlerIsUnregistered();
SingleObjectInvalidationSet set2 = GetStoredInvalidations();
ASSERT_EQ(kMax, set2.GetSize());
EXPECT_TRUE(set2.StartsWithUnknownVersion());
EXPECT_TRUE(set2.begin()->is_unknown_version());
EXPECT_EQ(kMax, static_cast<size_t>(set2.rbegin()->version()));
}
// Test acknowledgement.
TEST_F(UnackedInvalidationSetTest, Acknowledge) {
// inv2 is included in this test just to make sure invalidations that
// are supposed to be unaffected by this operation will be unaffected.
// We don't expect to be receiving acks or drops unless this flag is set.
// Not that it makes much of a difference in behavior.
unacked_invalidations_.SetHandlerIsRegistered();
Invalidation inv1 = Invalidation::Init(kObjectId_, 10, "payload");
Invalidation inv2 = Invalidation::InitUnknownVersion(kObjectId_);
AckHandle inv1_handle = inv1.ack_handle();
unacked_invalidations_.Add(inv1);
unacked_invalidations_.Add(inv2);
unacked_invalidations_.Acknowledge(inv1_handle);
SingleObjectInvalidationSet set = GetStoredInvalidations();
EXPECT_EQ(1U, set.GetSize());
EXPECT_TRUE(set.StartsWithUnknownVersion());
}
// Test drops.
TEST_F(UnackedInvalidationSetTest, Drop) {
// inv2 is included in this test just to make sure invalidations that
// are supposed to be unaffected by this operation will be unaffected.
// We don't expect to be receiving acks or drops unless this flag is set.
// Not that it makes much of a difference in behavior.
unacked_invalidations_.SetHandlerIsRegistered();
Invalidation inv1 = Invalidation::Init(kObjectId_, 10, "payload");
Invalidation inv2 = Invalidation::Init(kObjectId_, 15, "payload");
AckHandle inv1_handle = inv1.ack_handle();
unacked_invalidations_.Add(inv1);
unacked_invalidations_.Add(inv2);
unacked_invalidations_.Drop(inv1_handle);
SingleObjectInvalidationSet set = GetStoredInvalidations();
ASSERT_EQ(2U, set.GetSize());
EXPECT_TRUE(set.StartsWithUnknownVersion());
EXPECT_EQ(15, set.rbegin()->version());
}
class UnackedInvalidationSetSerializationTest
: public UnackedInvalidationSetTest {
public:
UnackedInvalidationSet SerializeDeserialize() {
std::unique_ptr<base::DictionaryValue> value =
unacked_invalidations_.ToValue();
UnackedInvalidationSet deserialized(kObjectId_);
deserialized.ResetFromValue(*value.get());
return deserialized;
}
};
TEST_F(UnackedInvalidationSetSerializationTest, Empty) {
UnackedInvalidationSet deserialized = SerializeDeserialize();
EXPECT_THAT(unacked_invalidations_, test_util::Eq(deserialized));
}
TEST_F(UnackedInvalidationSetSerializationTest, OneInvalidation) {
Invalidation inv = Invalidation::Init(kObjectId_, 10, "payload");
unacked_invalidations_.Add(inv);
UnackedInvalidationSet deserialized = SerializeDeserialize();
EXPECT_THAT(unacked_invalidations_, test_util::Eq(deserialized));
}
TEST_F(UnackedInvalidationSetSerializationTest, WithUnknownVersion) {
Invalidation inv1 = Invalidation::Init(kObjectId_, 10, "payload");
Invalidation inv2 = Invalidation::InitUnknownVersion(kObjectId_);
Invalidation inv3 = Invalidation::InitUnknownVersion(kObjectId_);
unacked_invalidations_.Add(inv1);
unacked_invalidations_.Add(inv2);
unacked_invalidations_.Add(inv3);
UnackedInvalidationSet deserialized = SerializeDeserialize();
EXPECT_THAT(unacked_invalidations_, test_util::Eq(deserialized));
}
TEST_F(UnackedInvalidationSetSerializationTest, ValidConversionFromMap) {
UnackedInvalidationsMap map;
Invalidation inv = Invalidation::Init(kObjectId_, 10, "payload");
unacked_invalidations_.Add(inv);
std::unique_ptr<base::DictionaryValue> dict =
unacked_invalidations_.ToValue();
bool result = UnackedInvalidationSet::DeserializeSetIntoMap(*dict, &map);
EXPECT_EQ(true, result);
auto item = map.find(kObjectId_);
ASSERT_NE(map.end(), item);
EXPECT_EQ(kObjectId_, item->second.object_id());
}
TEST_F(UnackedInvalidationSetSerializationTest, InvalidConversionFromMap) {
UnackedInvalidationsMap map;
base::DictionaryValue dict;
// Empty dictionary should fail.
EXPECT_FALSE(UnackedInvalidationSet::DeserializeSetIntoMap(dict, &map));
// Non-int source should fail.
dict.SetString("source", "foo");
EXPECT_FALSE(UnackedInvalidationSet::DeserializeSetIntoMap(dict, &map));
// Missing "name" should fail.
dict.SetString("source", base::IntToString(kObjectId_.source()));
EXPECT_FALSE(UnackedInvalidationSet::DeserializeSetIntoMap(dict, &map));
// The "invalidation-list" is not required, so add "name" to make valid.
dict.SetString("name", kObjectId_.name());
bool result = UnackedInvalidationSet::DeserializeSetIntoMap(dict, &map);
EXPECT_TRUE(result);
auto item = map.find(kObjectId_);
ASSERT_NE(map.end(), item);
EXPECT_EQ(kObjectId_, item->second.object_id());
}
} // namespace
} // namespace syncer
|
; void *obstack_blank_fast_callee(struct obstack *ob, int size)
SECTION code_clib
SECTION code_alloc_obstack
PUBLIC _obstack_blank_fast_callee
EXTERN asm_obstack_blank_fast
_obstack_blank_fast_callee:
pop af
pop hl
pop bc
push af
jp asm_obstack_blank_fast
|
; A100177: Structured meta-prism numbers, the n-th number from a structured n-gonal prism number sequence.
; 1,4,18,64,175,396,784,1408,2349,3700,5566,8064,11323,15484,20700,27136,34969,44388,55594,68800,84231,102124,122728,146304,173125,203476,237654,275968,318739,366300,418996,477184,541233,611524,688450,772416,863839,963148,1070784,1187200,1312861,1448244,1593838,1750144,1917675,2096956,2288524,2492928,2710729,2942500,3188826,3450304,3727543,4021164,4331800,4660096,5006709,5372308,5757574,6163200,6589891,7038364,7509348,8003584,8521825,9064836,9633394,10228288,10850319,11500300,12179056,12887424,13626253,14396404,15198750,16034176,16903579,17807868,18747964,19724800,20739321,21792484,22885258,24018624,25193575,26411116,27672264,28978048,30329509,31727700,33173686,34668544,36213363,37809244,39457300,41158656,42914449,44725828,46593954,48520000
mov $1,$0
add $1,1
mov $3,-2
add $3,$0
pow $0,2
sub $0,$3
mov $2,$1
mul $2,$1
mul $0,$2
div $0,2
|
/*
Copyright 2018-2021 <Pierre Constantineau, Julian Komaromy>
3-Clause BSD License
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************************************************************/
#include "firmware.h"
#include <Adafruit_LittleFS.h>
#include <Arduino.h>
#include <InternalFileSystem.h>
#include <bluefruit.h>
#ifdef WEKEY_HOST
#include "host.h"
#endif
#ifdef LED_MATRIX_ENABLE
#include "is31.h"
#endif
/**************************************************************************************************************************/
// Keyboard Matrix
byte rows[] MATRIX_ROW_PINS; // Contains the GPIO Pin Numbers defined in keyboard_config.h
byte columns[] MATRIX_COL_PINS; // Contains the GPIO Pin Numbers defined in keyboard_config.h
SoftwareTimer keyscantimer, batterytimer;
using namespace Adafruit_LittleFS_Namespace;
#define SETTINGS_FILE "/settings"
File file(InternalFS);
PersistentState keyboardconfig;
DynamicState keyboardstate;
BlueMicro_tone speaker(&keyboardconfig, &keyboardstate); /// A speaker to play notes and tunes...
led_handler statusLEDs(&keyboardconfig, &keyboardstate); /// Typically a Blue LED and a Red LED
#ifdef BLUEMICRO_CONFIGURED_DISPLAY
BlueMicro_Display OLED(&keyboardconfig, &keyboardstate); /// Typically a Blue LED and a Red LED
#endif
KeyScanner keys(&keyboardconfig, &keyboardstate);
Battery batterymonitor;
static std::vector<uint16_t> stringbuffer; // buffer for macros to type into...
static std::vector<std::array<uint8_t, 8>> reportbuffer;
/**************************************************************************************************************************/
void setupConfig() {
InternalFS.begin();
loadConfig();
keyboardstate.statusble = 0; // initialize to a known state.
keyboardstate.statuskb = 0; // initialize to a known state.
keyboardstate.user1 = 0; // initialize to a known state.
keyboardstate.user2 = 0; // initialize to a known state.
keyboardstate.user3 = 0; // initialize to a known state.
keyboardstate.helpmode = false;
keyboardstate.timestamp = millis();
keyboardstate.lastupdatetime = keyboardstate.timestamp;
keyboardstate.lastreporttime = 0;
keyboardstate.lastuseractiontime = 0;
keyboardstate.connectionState = CONNECTION_NONE;
keyboardstate.needReset = false;
keyboardstate.needUnpair = false;
keyboardstate.needFSReset = false;
keyboardstate.save2flash = false;
}
/**************************************************************************************************************************/
void loadConfig() {
file.open(SETTINGS_FILE, FILE_O_READ);
if (file) {
file.read(&keyboardconfig, sizeof(keyboardconfig));
file.close();
} else {
resetConfig();
saveConfig();
}
if (keyboardconfig.version != BLUEMICRO_CONFIG_VERSION) // SETTINGS_FILE format changed. we need to reset and re-save it.
{
resetConfig();
saveConfig();
}
keyboardconfig.enableSerial = (SERIAL_DEBUG_CLI_DEFAULT_ON == 1);
}
/**************************************************************************************************************************/
void resetConfig() {
keyboardconfig.version = BLUEMICRO_CONFIG_VERSION;
keyboardconfig.pinPWMLED = BACKLIGHT_LED_PIN;
keyboardconfig.pinRGBLED = WS2812B_LED_PIN;
keyboardconfig.pinBLELED = STATUS_BLE_LED_PIN;
keyboardconfig.pinKBLED = STATUS_KB_LED_PIN;
keyboardconfig.enablePWMLED = BACKLIGHT_PWM_ON;
keyboardconfig.enableRGBLED = WS2812B_LED_ON;
keyboardconfig.enableBLELED = BLE_LED_ACTIVE;
keyboardconfig.enableKBLED = STATUS_KB_LED_ACTIVE;
keyboardconfig.polarityBLELED = BLE_LED_POLARITY;
keyboardconfig.polarityKBLED = STATUS_KB_LED_POLARITY;
keyboardconfig.enableVCCSwitch = VCC_ENABLE_GPIO;
keyboardconfig.polarityVCCSwitch = VCC_DEFAULT_ON;
keyboardconfig.enableChargerControl = VCC_ENABLE_CHARGER;
keyboardconfig.polarityChargerControl = true;
#ifdef BLUEMICRO_CONFIGURED_DISPLAY
keyboardconfig.enableDisplay = true; // enabled if it's compiled with one...
#else
keyboardconfig.enableDisplay = false; // disabled if it's not compiled with one...
#endif
#ifdef SPEAKER_PIN
keyboardconfig.enableAudio = true; // enabled if it's compiled with one...
#else
keyboardconfig.enableAudio = false; // disabled if it's not compiled with one...
#endif
keyboardconfig.enableSerial = (SERIAL_DEBUG_CLI_DEFAULT_ON == 1);
keyboardconfig.mode = 0;
keyboardconfig.user1 = 0;
keyboardconfig.user2 = 0;
keyboardconfig.matrixscaninterval = HIDREPORTINGINTERVAL;
keyboardconfig.batteryinterval = BATTERYINTERVAL;
keyboardconfig.keysendinterval = HIDREPORTINGINTERVAL;
keyboardconfig.lowpriorityloopinterval = LOWPRIORITYLOOPINTERVAL;
keyboardconfig.lowestpriorityloopinterval = HIDREPORTINGINTERVAL * 2;
keyboardconfig.connectionMode = CONNECTION_MODE_AUTO;
keyboardconfig.BLEProfile = 0;
keyboardconfig.BLEProfileEdiv[0] = 0xFFFF;
keyboardconfig.BLEProfileEdiv[1] = 0xFFFF;
keyboardconfig.BLEProfileEdiv[2] = 0xFFFF;
strcpy(keyboardconfig.BLEProfileName[0], "unpaired");
strcpy(keyboardconfig.BLEProfileName[1], "unpaired");
strcpy(keyboardconfig.BLEProfileName[2], "unpaired");
}
/**************************************************************************************************************************/
void saveConfig() {
InternalFS.remove(SETTINGS_FILE);
if (file.open(SETTINGS_FILE, FILE_O_WRITE)) {
file.write((uint8_t *)&keyboardconfig, sizeof(keyboardconfig));
file.close();
}
}
/**************************************************************************************************************************/
// put your setup code here, to run once:
/**************************************************************************************************************************/
// cppcheck-suppress unusedFunction
void setup() {
setupGpio(); // checks that NFC functions on GPIOs are disabled.
setupWDT();
#ifdef BLUEMICRO_CONFIGURED_DISPLAY
OLED.begin();
#endif
setupConfig();
#ifdef SPEAKER_PIN
speaker.setSpeakerPin(SPEAKER_PIN);
#endif
if (keyboardconfig.enableSerial) {
Serial.begin(115200);
while ( !Serial ) delay(10); // for nrf52840 with native usb
Serial.println(" ____ _ __ __ _ ____ _ _____ ");
Serial.println("| __ )| |_ _ ___| \\/ (_) ___ _ __ ___ | __ )| | | ____|");
Serial.println("| _ \\| | | | |/ _ \\ |\\/| | |/ __| '__/ _ \\ | _ \\| | | _| ");
Serial.println("| |_) | | |_| | __/ | | | | (__| | | (_) | | |_) | |___| |___ ");
Serial.println("|____/|_|\\__,_|\\___|_| |_|_|\\___|_| \\___/___|____/|_____|_____|");
Serial.println(" |_____| ");
Serial.println("");
Serial.println("Type 'h' to get a list of commands with descriptions");
}
LOG_LV1("BLEMIC", "Starting %s", DEVICE_NAME);
if (keyboardconfig.enableVCCSwitch) {
switchVCC(keyboardconfig.polarityVCCSwitch); // turn on VCC when starting up if needed.
}
if (keyboardconfig.enableChargerControl) {
switchCharger(keyboardconfig.polarityChargerControl); // turn on Charger when starting up if needed.
}
keyscantimer.begin(keyboardconfig.matrixscaninterval, keyscantimer_callback);
// batterytimer.begin(keyboardconfig.batteryinterval, batterytimer_callback);
bt_setup(keyboardconfig.BLEProfile);
usb_setup(); // does nothing for 832 - see usb.cpp
// Set up keyboard matrix and start advertising
setupKeymap(); // this is where we can change the callback for our LEDs...
setupMatrix();
bt_startAdv();
keyscantimer.start();
// batterytimer.start();
stringbuffer.clear();
reportbuffer.clear();
if (keyboardconfig.enablePWMLED) {
setupPWM(
keyboardconfig.pinPWMLED); // PWM contributes 500uA to the bottom line on a 840 device. see
// https://devzone.nordicsemi.com/f/nordic-q-a/40912/pwm-power-consumption-nrf52840 (there is no electrical specification)
}
if (keyboardconfig.enableRGBLED) {
setupRGB(); // keyboardconfig.pinRGBLED
}
statusLEDs.enable();
statusLEDs.hello(); // blinks Status LEDs a couple as last step of setup.
Scheduler.startLoop(LowestPriorityloop, 1024, TASK_PRIO_LOWEST, "l1"); // this loop contains LED,RGB & PWM and Display updates.
// Scheduler.startLoop(NormalPriorityloop, 1024, TASK_PRIO_NORMAL, "n1"); // this has nothing in it...
#ifdef BLUEMICRO_CONFIGURED_DISPLAY
if (keyboardconfig.enableDisplay) {
OLED.changeUpdateMode(DISPLAY_UPDATE_STATUS);
} else {
OLED.sleep();
}
#endif
speaker.playTone(TONE_STARTUP);
speaker.playTone(TONE_BLE_PROFILE);
#ifdef WEKEY_HOST
host_init();
#endif
#ifdef LED_MATRIX_ENABLE
is31_init();
#endif
};
/**************************************************************************************************************************/
//
/**************************************************************************************************************************/
void setupMatrix(void) {
// inits all the columns as INPUT
for (const auto &column : columns) {
LOG_LV2("BLEMIC", "Setting to INPUT Column: %i", column);
pinMode(column, INPUT);
}
// inits all the rows as INPUT_PULLUP
for (const auto &row : rows) {
LOG_LV2("BLEMIC", "Setting to INPUT_PULLUP Row: %i", row);
pinMode(row, INPUT_PULLUP);
}
};
/**************************************************************************************************************************/
// Keyboard Scanning
/**************************************************************************************************************************/
#if DIODE_DIRECTION == COL2ROW
#define writeRow(r) digitalWrite(r, LOW)
#define modeCol(c) pinMode(c, INPUT_PULLUP)
#ifdef NRF52840_XXAA
#define gpioIn (((uint64_t)(NRF_P1->IN) ^ 0xffffffff) << 32) | (NRF_P0->IN) ^ 0xffffffff
#else
#define gpioIn (NRF_GPIO->IN) ^ 0xffffffff
#endif
#else
#define writeRow(r) digitalWrite(r, HIGH)
#define modeCol(c) pinMode(c, INPUT_PULLDOWN)
#ifdef NRF52840_XXAA
#define gpioIn (((uint64_t)NRF_P1->IN) << 32) | (NRF_P0->IN)
#else
#define gpioIn NRF_GPIO->IN
#endif
#endif
#ifdef NRF52840_XXAA
#define PINDATATYPE uint64_t
#else
#define PINDATATYPE uint32_t
#endif
/**************************************************************************************************************************/
// THIS FUNCTION TAKES CARE OF SCANNING THE MATRIX AS WELL AS DEBOUNCING THE KEY PRESSES
// IF YOU ARE USING A DIFFERENT METHOD TO READ/WRITE TO GPIOS (SUCH AS SHIFT REGISTERS OR GPIO EXPANDERS), YOU WILL
// NEED TO RE-WORK THIS ROUTINE. IDEALLY WE SHOULD HAVE THIS AS A COMPILE-TIME OPTION TO SWITCH BETWEEN ROUTINES.
/**************************************************************************************************************************/
void scanMatrix() {
keyboardstate.timestamp = millis(); // lets call it once per scan instead of once per key in the matrix
static PINDATATYPE pindata[ORIGIN_MATRIX_ROWS][DEBOUNCETIME];
static uint8_t head = 0; // points us to the head of the debounce array;
for (int i = 0; i < ORIGIN_MATRIX_COLS; ++i) {
modeCol(columns[i]);
}
for (int j = 0; j < ORIGIN_MATRIX_ROWS; ++j) {
// set the current row as OUPUT and LOW
PINDATATYPE pinreg = 0;
pinMode(rows[j], OUTPUT);
writeRow(rows[j]);
nrfx_coredep_delay_us(1); // need for the GPIO lines to settle down electrically before reading.
pindata[j][head] = gpioIn; // press is active high regardless of diode dir
// debounce happens here - we want to press a button as soon as possible, and release it only when all bounce has left
for (int d = 0; d < DEBOUNCETIME; ++d)
pinreg |= pindata[j][d];
for (int i = 0; i < ORIGIN_MATRIX_COLS; ++i) {
int ulPin = g_ADigitalPinMap[columns[i]];
if ((pinreg >> ulPin) & 1)
KeyScanner::press(keyboardstate.timestamp, j, i);
else
KeyScanner::release(keyboardstate.timestamp, j, i);
}
pinMode(rows[j], INPUT); // 'disables' the row that was just scanned
}
for (int i = 0; i < ORIGIN_MATRIX_COLS; ++i) { // Scanning done, disabling all columns
pinMode(columns[i], INPUT);
}
head++;
if (head >= DEBOUNCETIME)
head = 0; // reset head to 0 when we reach the end of our buffer
#ifdef WEKEY_HOST
host_scan();
for (int j = 0; j < HOST_MATRIX_ROWS; j++) {
for (int i = 0; i < HOST_MATRIX_COLS; i++) {
if (host_matrix_is_on(j, i)) {
KeyScanner::press(keyboardstate.timestamp, ORIGIN_MATRIX_ROWS + j, ORIGIN_MATRIX_COLS + i);
/*
if (keyboardconfig.enableSerial) {
Serial.print("Pressed...");
Serial.print("[");
Serial.print(j);
Serial.print("]");
Serial.print("[");
Serial.print(i);
Serial.println("]");
}
*/
} else {
KeyScanner::release(keyboardstate.timestamp, ORIGIN_MATRIX_ROWS + j, ORIGIN_MATRIX_COLS + i);
}
}
}
#endif
}
/**************************************************************************************************************************/
// THIS IS THE DEFAULT process_user_macros FUNCTION WHICH IS OVERRIDEN BY USER ONE.
/**************************************************************************************************************************/
#if USER_MACRO_FUNCTION == 1
void process_user_macros(uint16_t macroid) {
switch ((macroid)) {
case MC(KC_A):
addStringToQueue("Macro Example 1");
break;
}
}
#endif
void UpdateQueue() {
stringbuffer.insert(stringbuffer.end(), combos.keycodebuffertosend.rbegin(), combos.keycodebuffertosend.rend());
combos.keycodebuffertosend.clear();
}
/**************************************************************************************************************************/
// macro string queue management
/**************************************************************************************************************************/
void addStringToQueue(const char *str) {
auto it = stringbuffer.begin();
char ch;
while ((ch = *str++) != 0) {
uint8_t modifier = (hid_ascii_to_keycode[(uint8_t)ch][0]) ? KEYBOARD_MODIFIER_LEFTSHIFT : 0;
uint8_t keycode = hid_ascii_to_keycode[(uint8_t)ch][1];
uint16_t keyreport = MOD(modifier << 8, keycode);
it = stringbuffer.insert(it, keyreport);
}
}
/**************************************************************************************************************************/
/**************************************************************************************************************************/
void addKeycodeToQueue(const uint16_t keycode) {
auto it = stringbuffer.begin();
auto hidKeycode = static_cast<uint8_t>(keycode & 0x00FF);
if (hidKeycode >= KC_A && hidKeycode <= KC_EXSEL) // only insert keycodes if they are valid keyboard codes...
{
it = stringbuffer.insert(it, keycode);
}
}
void addKeycodeToQueue(const uint16_t keycode, const uint8_t modifier) {
auto it = stringbuffer.begin();
auto hidKeycode = static_cast<uint8_t>(keycode & 0x00FF);
// auto extraModifiers = static_cast<uint8_t>((keycode & 0xFF00) >> 8);
if (hidKeycode >= KC_A && hidKeycode <= KC_EXSEL) // only insert keycodes if they are valid keyboard codes...
{
uint16_t keyreport = MOD(modifier << 8, hidKeycode);
it = stringbuffer.insert(it, keyreport);
}
}
/**************************************************************************************************************************/
/**************************************************************************************************************************/
void process_keyboard_function(uint16_t keycode) {
char buffer[50];
uint8_t intval;
switch (keycode) {
case RESET:
NVIC_SystemReset();
break;
case DEBUG:
keyboardconfig.enableSerial = !keyboardconfig.enableSerial;
keyboardstate.save2flash = true;
keyboardstate.needReset = true;
break;
case EEPROM_RESET:
keyboardstate.needFSReset = true;
break;
case CLEAR_BONDS:
// Bluefruit.clearBonds(); //removed in next BSP?
if (keyboardstate.connectionState == CONNECTION_BT)
keyboardstate.needUnpair = true;
// Bluefruit.Central.clearBonds();
break;
case DFU:
speaker.playTone(TONE_SLEEP);
speaker.playAllQueuedTonesNow();
enterOTADfu();
break;
case SERIAL_DFU:
speaker.playTone(TONE_SLEEP);
speaker.playAllQueuedTonesNow();
enterSerialDfu();
break;
case UF2_DFU:
speaker.playTone(TONE_SLEEP);
speaker.playAllQueuedTonesNow();
enterUf2Dfu();
break;
case HELP_MODE:
keyboardstate.helpmode = !keyboardstate.helpmode;
break;
case OUT_AUTO:
keyboardconfig.connectionMode = CONNECTION_MODE_AUTO;
if (keyboardstate.helpmode) {
addStringToQueue("Automatic USB/BLE - Active");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("USB Only");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("BLE Only");
addKeycodeToQueue(KC_ENTER);
}
break;
case OUT_USB:
#ifdef NRF52840_XXAA // only the 840 has USB available.
keyboardconfig.connectionMode = CONNECTION_MODE_USB_ONLY;
if (keyboardstate.helpmode) {
addStringToQueue("Automatic USB/BLE");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("USB Only - Active");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("BLE Only");
addKeycodeToQueue(KC_ENTER);
}
#else
if (keyboardstate.helpmode) {
addStringToQueue("USB not available on NRF52832");
addKeycodeToQueue(KC_ENTER);
}
#endif
break;
case OUT_BT:
keyboardconfig.connectionMode = CONNECTION_MODE_BLE_ONLY;
if (keyboardstate.helpmode) {
addStringToQueue("Automatic USB/BLE");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("USB Only");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("BLE Only - Active");
addKeycodeToQueue(KC_ENTER);
}
break;
// BACKLIGHT FUNCTIONS
case BL_TOGG:
if (keyboardstate.helpmode) {
addStringToQueue("BL_TOGG");
}
stepPWMMode();
break;
case BL_STEP: // step through modes
if (keyboardstate.helpmode) {
addStringToQueue("BL_STEP");
}
stepPWMMode();
break;
case BL_ON:
if (keyboardstate.helpmode) {
addStringToQueue("BL_ON");
}
setPWMMode(3);
PWMSetMaxVal();
break;
case BL_OFF:
if (keyboardstate.helpmode) {
addStringToQueue("BL_OFF");
}
setPWMMode(0);
break;
case BL_INC:
if (keyboardstate.helpmode) {
addStringToQueue("BL_INC");
}
incPWMMaxVal();
break;
case BL_DEC:
if (keyboardstate.helpmode) {
addStringToQueue("BL_DEC");
}
decPWMMaxVal();
break;
case BL_BRTG:
if (keyboardstate.helpmode) {
addStringToQueue("BL_BRTG");
}
setPWMMode(2);
break;
case BL_REACT:
if (keyboardstate.helpmode) {
addStringToQueue("BL_REACT");
}
setPWMMode(1);
PWMSetMaxVal();
break;
case BL_STEPINC:
if (keyboardstate.helpmode) {
addStringToQueue("BL_STEPINC");
}
incPWMStepSize();
break;
case BL_STEPDEC:
if (keyboardstate.helpmode) {
addStringToQueue("BL_STEPDEC");
}
decPWMStepSize();
break;
case RGB_TOG:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_TOG");
}
break;
case RGB_MODE_FORWARD:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_MODE_FORWARD");
}
break;
case RGB_MODE_REVERSE:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_MODE_REVERSE");
}
break;
case RGB_HUI:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_HUI");
}
break;
case RGB_HUD:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_HUD");
}
break;
case RGB_SAI:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_SAI");
}
break;
case RGB_SAD:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_SAD");
}
break;
case RGB_VAI:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_VAI");
}
break;
case RGB_VAD:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_VAD");
}
break;
case RGB_MODE_PLAIN:
if (keyboardstate.helpmode) {
addStringToQueue("RGB_MODE_PLAIN");
}
updateRGBmode(RGB_MODE_PLAIN);
break;
case RGB_MODE_BREATHE:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_MODE_BREATHE");}
updateRGBmode(RGB_MODE_BREATHE);
break;
case RGB_MODE_RAINBOW:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_MODE_RAINBOW");}
updateRGBmode(RGB_MODE_RAINBOW);
break;
case RGB_MODE_SWIRL:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_MODE_SWIRL");}
updateRGBmode(RGB_MODE_SWIRL);
break;
case RGB_MODE_SNAKE:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_MODE_SNAKE");}
updateRGBmode(RGB_MODE_SNAKE);
break;
case RGB_MODE_KNIGHT:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_MODE_KNIGHT");}
updateRGBmode(RGB_MODE_KNIGHT);
break;
case RGB_MODE_XMAS:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_MODE_XMAS");}
updateRGBmode(RGB_MODE_XMAS);
break;
case RGB_MODE_GRADIENT:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_MODE_GRADIENT");}
updateRGBmode(RGB_MODE_GRADIENT);
break;
case RGB_MODE_RGBTEST:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_MODE_RGBTEST");}
updateRGBmode(RGB_MODE_RGBTEST);
break;
case RGB_SPI:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_SPI");}
break;
case RGB_SPD:
if ( keyboardstate.helpmode) {addStringToQueue("RGB_SPD");}
break;
case PRINT_BATTERY:
intval = batterymonitor.vbat_per;
switch (batterymonitor.batt_type)
{
case BATT_UNKNOWN:
snprintf (buffer, sizeof(buffer), "VDD = %.0f mV, VBatt = %.0f mV", batterymonitor.vbat_vdd*1.0, batterymonitor.vbat_mv*1.0);
break;
case BATT_CR2032:
if (intval>99)
{
snprintf (buffer, sizeof(buffer), "VDD = %.0f mV (%4d %%)", batterymonitor.vbat_mv*1.0, intval);
}
else
{
snprintf (buffer, sizeof(buffer), "VDD = %.0f mV (%3d %%)", batterymonitor.vbat_mv*1.0, intval);
}
break;
case BATT_LIPO:
if (intval>99)
{
sprintf (buffer, "LIPO = %.0f mV (%4d %%)", batterymonitor.vbat_mv*1.0, intval);
}
else
{
sprintf (buffer, "LIPO = %.0f mV (%3d %%)", batterymonitor.vbat_mv*1.0, intval);
}
break;
case BATT_VDDH:
if (intval>99)
{
sprintf (buffer, "LIPO = %.0f mV (%4d %%)", batterymonitor.vbat_mv*1.0, intval);
}
else
{
sprintf (buffer, "LIPO = %.0f mV (%3d %%)", batterymonitor.vbat_mv*1.0, intval);
}
break;
}
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
break;
case PRINT_INFO:
addStringToQueue("Keyboard Name : " DEVICE_NAME " ");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("Keyboard Model : " DEVICE_MODEL " ");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("Keyboard Mfg : " MANUFACTURER_NAME " ");
addKeycodeToQueue(KC_ENTER);
addStringToQueue("BSP Library : " ARDUINO_BSP_VERSION " ");
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "Bootloader : %s", getBootloaderVersion());
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "Serial No : %s", getMcuUniqueID());
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "Device Power : %f", DEVICE_POWER * 1.0);
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
switch (keyboardconfig.connectionMode) {
case CONNECTION_MODE_AUTO:
addStringToQueue("CONNECTION_MODE_AUTO");
addKeycodeToQueue(KC_ENTER);
break;
case CONNECTION_MODE_USB_ONLY:
addStringToQueue("CONNECTION_MODE_USB_ONLY");
addKeycodeToQueue(KC_ENTER);
break;
case CONNECTION_MODE_BLE_ONLY:
addStringToQueue("CONNECTION_MODE_BLE_ONLY");
addKeycodeToQueue(KC_ENTER);
break;
}
switch (keyboardstate.connectionState) {
case CONNECTION_USB:
addStringToQueue("CONNECTION_USB");
addKeycodeToQueue(KC_ENTER);
break;
case CONNECTION_BT:
addStringToQueue("CONNECTION_BLE");
addKeycodeToQueue(KC_ENTER);
break;
case CONNECTION_NONE:
addStringToQueue("CONNECTION_NONE");
addKeycodeToQueue(KC_ENTER);
break;
}
break;
case PRINT_BLE:
addStringToQueue("Keyboard Name: " DEVICE_NAME " ");
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "Device Power : %i", DEVICE_POWER);
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "Filter RSSI : %i", FILTER_RSSI_BELOW_STRENGTH);
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
addStringToQueue("Type\t RSSI\t name");
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "cent\t %i\t %s", keyboardstate.rssi_cent, keyboardstate.peer_name_cent);
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "prph\t %i\t %s", keyboardstate.rssi_prph, keyboardstate.peer_name_prph);
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "cccd\t %i\t %s", keyboardstate.rssi_cccd, keyboardstate.peer_name_cccd);
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "Profile 1: %s", keyboardconfig.BLEProfileName[0]);
addStringToQueue(buffer);
if (keyboardconfig.BLEProfile == 0)
addStringToQueue(" (active)");
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "Profile 2: %s", keyboardconfig.BLEProfileName[1]);
addStringToQueue(buffer);
if (keyboardconfig.BLEProfile == 1)
addStringToQueue(" (active)");
addKeycodeToQueue(KC_ENTER);
sprintf(buffer, "Profile 3: %s", keyboardconfig.BLEProfileName[2]);
addStringToQueue(buffer);
if (keyboardconfig.BLEProfile == 2)
addStringToQueue(" (active)");
addKeycodeToQueue(KC_ENTER);
addKeycodeToQueue(KC_ENTER);
ble_gap_addr_t gap_addr;
gap_addr = bt_getMACAddr();
sprintf(buffer, "BT MAC Addr: %02X:%02X:%02X:%02X:%02X:%02X", gap_addr.addr[5], gap_addr.addr[4], gap_addr.addr[3], gap_addr.addr[2], gap_addr.addr[1],
gap_addr.addr[0]);
addStringToQueue(buffer);
addKeycodeToQueue(KC_ENTER);
addKeycodeToQueue(KC_ENTER);
break;
case PRINT_HELP:
break;
case SLEEP_NOW:
if (keyboardstate.connectionState != CONNECTION_USB)
sleepNow();
break;
case WIN_A_GRAVE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_2, KC_KP_4) break; // Alt 0224 a grave
case WIN_A_ACUTE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_2, KC_KP_5) break; // Alt 0225 a acute
case WIN_A_CIRCU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_2, KC_KP_6) break; // Alt 0226 a circumflex
case WIN_A_TILDE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_2, KC_KP_7) break; // Alt 0227 a tilde
case WIN_A_UMLAU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_2, KC_KP_8) break; // Alt 0228 a umlaut
case WIN_A_GRAVE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_9, KC_KP_2) break; // Alt 0192 A grave
case WIN_A_ACUTE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_9, KC_KP_3) break; // Alt 0193 A acute
case WIN_A_CIRCU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_9, KC_KP_4) break; // Alt 0194 A circumflex
case WIN_A_TILDE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_9, KC_KP_5) break; // Alt 0195 A tilde
case WIN_A_UMLAU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_9, KC_KP_6) break; // Alt 0196 A umlaut
case WIN_C_CEDIL:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_1) break; // Alt 0231 c cedilla
case WIN_C_CEDIL_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_9, KC_KP_9) break; // Alt 0199 C cedilla
case WIN_E_GRAVE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_2) break;
case WIN_E_ACUTE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_3) break;
case WIN_E_CIRCU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_4) break;
case WIN_E_UMLAU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_5) break;
case WIN_I_GRAVE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_6) break; // Alt 0236 i grave
case WIN_I_ACUTE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_7) break; // Alt 0237 i acute
case WIN_I_CIRCU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_8) break; // Alt 0238 i circumflex
case WIN_I_UMLAU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_3, KC_KP_9) break; // Alt 0239 i umlaut
case WIN_I_GRAVE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_0, KC_KP_4) break; // Alt 0204 I grave
case WIN_I_ACUTE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_0, KC_KP_5) break; // Alt 0205 I acute
case WIN_I_CIRCU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_0, KC_KP_6) break; // Alt 0206 I circumflex
case WIN_I_UMLAU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_0, KC_KP_7) break; // Alt 0207 I umlaut
case WIN_N_TILDE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_6, KC_KP_4) break; // Alt 164 n tilde
case WIN_N_TILDE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_6, KC_KP_5) break; // Alt 165 N tilde
case WIN_O_GRAVE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_4, KC_KP_2) break; // Alt 0242 o grave
case WIN_O_ACUTE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_4, KC_KP_3) break; // Alt 0243 o acute
case WIN_O_CIRCU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_4, KC_KP_4) break; // Alt 0244 o circumflex
case WIN_O_TILDE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_4, KC_KP_5) break; // Alt 0245 o tilde
case WIN_O_UMLAU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_4, KC_KP_6) break; // Alt 0246 o umlaut
case WIN_O_GRAVE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_1, KC_KP_0) break; // Alt 0210 O grave
case WIN_O_ACUTE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_1, KC_KP_1) break; // Alt 0211 O acute
case WIN_O_CIRCU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_1, KC_KP_2) break; // Alt 0212 O circumflex
case WIN_O_TILDE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_1, KC_KP_3) break; // Alt 0213 O tilde
case WIN_O_UMLAU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_1, KC_KP_4) break; // Alt 0214 O umlaut
case WIN_S_CARON:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_5, KC_KP_4) break; // Alt 0154 s caron
case WIN_S_CARON_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_3, KC_KP_8) break; // Alt 0138 S caron
case WIN_U_GRAVE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_4, KC_KP_9) break; // Alt 0249 u grave
case WIN_U_ACUTE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_5, KC_KP_0) break; // Alt 0250 u acute
case WIN_U_CIRCU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_5, KC_KP_1) break; // Alt 0251 u circumflex
case WIN_U_UMLAU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_5, KC_KP_2) break; // Alt 0252 u umlaut
case WIN_U_GRAVE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_1, KC_KP_1) break; // Alt 0217 U grave
case WIN_U_ACUTE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_1, KC_KP_8) break; // Alt 0218 U acute
case WIN_U_CIRCU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_1, KC_KP_9) break; // Alt 0219 U circumflex
case WIN_U_UMLAU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_2, KC_KP_0) break; // Alt 0220 U umlaut
case WIN_Y_ACUTE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_5, KC_KP_3) break; // Alt 0253 y acute
case WIN_Y_UMLAU:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_5, KC_KP_5) break; // Alt 0255 y umlaut
case WIN_Y_ACUTE_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_2, KC_KP_2, KC_KP_1) break; // Alt 0221 Y tilde
case WIN_Y_UMLAU_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_5, KC_KP_9) break; // Alt 0159 Y umlaut
case WIN_Z_CARON:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_5, KC_KP_4) break; // Alt 0154 z caron
case WIN_Z_CARON_CAP:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_3, KC_KP_8) break; // Alt 0138 Z caron
case SYM_DEGREE:
EXPAND_ALT_CODE(KC_KP_0, KC_KP_1, KC_KP_7, KC_KP_6) break; // Alt 0176 degree symbol
case BLEPROFILE_1:
// if (keyboardstate.connectionState != CONNECTION_USB) // reseting/rebooting KB when BLE Profile switching on USB would be ennoying...
{
#ifdef ARDUINO_NRF52_COMMUNITY
keyboardconfig.BLEProfile = 0;
keyboardstate.save2flash = true;
keyboardstate.needReset = true;
#endif
#ifdef ARDUINO_NRF52_ADAFRUIT
; // do nothing since the Adafruit BSP doesn't support ediv.
#endif
}
break;
case BLEPROFILE_2:
// if (keyboardstate.connectionState != CONNECTION_USB) // reseting/rebooting KB when BLE Profile switching on USB would be ennoying...
{
#ifdef ARDUINO_NRF52_COMMUNITY
keyboardconfig.BLEProfile = 1;
keyboardstate.save2flash = true;
keyboardstate.needReset = true;
#endif
#ifdef ARDUINO_NRF52_ADAFRUIT
; // do nothing since the Adafruit BSP doesn't support ediv.
#endif
}
break;
case BLEPROFILE_3:
// if (keyboardstate.connectionState != CONNECTION_USB) // reseting/rebooting KB when BLE Profile switching on USB would be ennoying...
{
#ifdef ARDUINO_NRF52_COMMUNITY
keyboardconfig.BLEProfile = 2;
keyboardstate.save2flash = true;
keyboardstate.needReset = true;
#endif
#ifdef ARDUINO_NRF52_ADAFRUIT
; // do nothing since the Adafruit BSP doesn't support ediv.
#endif
}
break;
case BATTERY_CALC_DEFAULT:
batterymonitor.setmvToPercentCallback(mvToPercent_default);
batterymonitor.updateBattery(); // force an update
break;
case BATTERY_CALC_TEST:
batterymonitor.setmvToPercentCallback(mvToPercent_test);
batterymonitor.updateBattery(); // force an update
break;
}
}
/**************************************************************************************************************************/
/**************************************************************************************************************************/
void process_user_special_keys() {
uint8_t mods = KeyScanner::currentReport[0];
LOG_LV1("SPECIAL", "PROCESS: %i %i %i %i %i %i %i %i %i", KeyScanner::special_key, mods, KeyScanner::currentReport[1], KeyScanner::currentReport[2],
KeyScanner::currentReport[3], KeyScanner::currentReport[4], KeyScanner::currentReport[5], KeyScanner::currentReport[6], KeyScanner::bufferposition);
switch (KeyScanner::special_key) {
case KS(KC_ESC):
switch (mods) {
case 0:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_ESC;
KeyScanner::reportChanged = true;
break;
case BIT_LCTRL:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_GRAVE;
KeyScanner::reportChanged = true;
KeyScanner::currentReport[0] = 0;
break;
case BIT_LSHIFT:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_GRAVE;
KeyScanner::reportChanged = true;
KeyScanner::currentReport[0] = BIT_LSHIFT;
break;
case BIT_LALT:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_GRAVE;
KeyScanner::reportChanged = true;
KeyScanner::currentReport[0] = 0;
break;
case BIT_LGUI:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_GRAVE;
KeyScanner::reportChanged = true;
KeyScanner::currentReport[0] = 0;
break;
case BIT_RCTRL:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_GRAVE;
KeyScanner::reportChanged = true;
KeyScanner::currentReport[0] = 0;
break;
case BIT_RSHIFT:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_GRAVE;
KeyScanner::reportChanged = true;
KeyScanner::currentReport[0] = 0;
break;
case BIT_RALT:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_GRAVE;
KeyScanner::reportChanged = true;
KeyScanner::currentReport[0] = 0;
break;
case BIT_RGUI:
KeyScanner::currentReport[KeyScanner::bufferposition] = KC_GRAVE;
KeyScanner::reportChanged = true;
KeyScanner::currentReport[0] = 0;
break;
}
break;
default:
break;
}
}
/**************************************************************************************************************************/
// Communication with computer and other boards
/**************************************************************************************************************************/
void sendKeyPresses() {
KeyScanner::getReport(); // get state data - Data is in KeyScanner::currentReport
if (KeyScanner::special_key > 0) {
process_user_special_keys();
KeyScanner::special_key = 0;
}
if (KeyScanner::macro > 0) {
process_user_macros(KeyScanner::macro);
KeyScanner::macro = 0;
}
UpdateQueue();
if (!stringbuffer.empty()) // if the macro buffer isn't empty, send the first character of the buffer... which is located at the back of the queue
{
std::array<uint8_t, 8> reportarray = {0, 0, 0, 0, 0, 0, 0, 0};
uint16_t keyreport = stringbuffer.back();
stringbuffer.pop_back();
reportarray[0] = static_cast<uint8_t>((keyreport & 0xFF00) >> 8); // mods
reportarray[1] = static_cast<uint8_t>(keyreport & 0x00FF);
auto buffer_iterator = reportbuffer.begin();
buffer_iterator = reportbuffer.insert(buffer_iterator, reportarray);
uint16_t lookahead_keyreport = stringbuffer.back();
if (lookahead_keyreport == keyreport) // if the next key is the same, make sure to send a key release before sending it again... but keep the mods.
{
reportarray[0] = static_cast<uint8_t>((keyreport & 0xFF00) >> 8); // mods;
reportarray[1] = 0;
buffer_iterator = reportbuffer.begin();
buffer_iterator = reportbuffer.insert(buffer_iterator, reportarray);
}
}
if (!reportbuffer.empty()) // if the report buffer isn't empty, send the first character of the buffer... which is located at the end of the queue
{
std::array<uint8_t, 8> reportarray = reportbuffer.back();
reportbuffer.pop_back();
switch (keyboardstate.connectionState) {
case CONNECTION_USB:
usb_sendKeys(reportarray);
delay(keyboardconfig.keysendinterval * 2);
break;
case CONNECTION_BT:
bt_sendKeys(reportarray);
delay(keyboardconfig.keysendinterval * 2);
break;
case CONNECTION_NONE: // save the report for when we reconnect
auto it = reportbuffer.end();
it = reportbuffer.insert(it, reportarray);
break;
}
if (reportbuffer.empty()) // make sure to send an empty report when done...
{
switch (keyboardstate.connectionState) {
case CONNECTION_USB:
usb_sendKeys({0, 0, 0, 0, 0, 0, 0, 0});
delay(keyboardconfig.keysendinterval * 2);
break;
case CONNECTION_BT:
bt_sendKeys({0, 0, 0, 0, 0, 0, 0, 0});
delay(keyboardconfig.keysendinterval * 2);
break;
case CONNECTION_NONE: // save the report for when we reconnect
auto it = reportbuffer.end();
it = reportbuffer.insert(it, {0, 0, 0, 0, 0, 0, 0, 0});
break;
}
}
// KeyScanner::processingmacros=0;
} else if ((KeyScanner::reportChanged)) // any new key presses anywhere?
{
switch (keyboardstate.connectionState) {
case CONNECTION_USB:
usb_sendKeys(KeyScanner::currentReport);
break;
case CONNECTION_BT:
bt_sendKeys(KeyScanner::currentReport);
break;
case CONNECTION_NONE: // save the report for when we reconnect
auto it = reportbuffer.begin();
it = reportbuffer.insert(it, {KeyScanner::currentReport[0], KeyScanner::currentReport[1], KeyScanner::currentReport[2], KeyScanner::currentReport[3],
KeyScanner::currentReport[4], KeyScanner::currentReport[5], KeyScanner::currentReport[6], KeyScanner::currentReport[7]});
break;
}
LOG_LV1("MXSCAN", "SEND: %i %i %i %i %i %i %i %i %i ", keyboardstate.timestamp, KeyScanner::currentReport[0], KeyScanner::currentReport[1],
KeyScanner::currentReport[2], KeyScanner::currentReport[3], KeyScanner::currentReport[4], KeyScanner::currentReport[5],
KeyScanner::currentReport[6], KeyScanner::currentReport[7]);
} else if (KeyScanner::specialfunction > 0) {
process_keyboard_function(KeyScanner::specialfunction);
KeyScanner::specialfunction = 0;
} else if (KeyScanner::consumer > 0) {
switch (keyboardstate.connectionState) {
case CONNECTION_USB:
usb_sendMediaKey(KeyScanner::consumer);
break;
case CONNECTION_BT:
bt_sendMediaKey(KeyScanner::consumer);
break;
case CONNECTION_NONE:
speaker.playTone(TONE_BLE_DISCONNECT);
break; // we have lost a report!
}
KeyScanner::consumer = 0;
} else if (KeyScanner::mouse > 0) {
switch (keyboardstate.connectionState) {
case CONNECTION_USB:
usb_sendMouseKey(KeyScanner::mouse);
break;
case CONNECTION_BT:
bt_sendMouseKey(KeyScanner::mouse);
break;
case CONNECTION_NONE:
speaker.playTone(TONE_BLE_DISCONNECT);
break; // we have lost a report!
}
KeyScanner::mouse = 0;
}
#if BLE_PERIPHERAL == 1 | BLE_CENTRAL == 1 /**************************************************/
if (KeyScanner::layerChanged || (keyboardstate.timestamp - keyboardstate.lastupdatetime > 1000)) // layer comms
{
keyboardstate.lastupdatetime = keyboardstate.timestamp;
sendlayer(KeyScanner::localLayer);
LOG_LV1("MXSCAN", "Layer %i %i", keyboardstate.timestamp, KeyScanner::localLayer);
KeyScanner::layerChanged = false; // mark layer as "not changed" since last update
}
#endif /**************************************************/
}
// keyscantimer is being called instead
/**************************************************************************************************************************/
void keyscantimer_callback(TimerHandle_t _handle) {
// timers have NORMAL priorities (HIGHEST>HIGH>NORMAL>LOW>LOWEST)
// since timers are repeated non stop, we dont want the duration of code running within the timer to vary and potentially
// go longer than the interval time.
#if MATRIX_SCAN == 1
scanMatrix();
#endif
#if SEND_KEYS == 1
sendKeyPresses();
#endif
keyboardstate.lastuseractiontime = max(KeyScanner::getLastPressed(), keyboardstate.lastuseractiontime); // use the latest time to check for sleep...
unsigned long timesincelastkeypress = keyboardstate.timestamp - keyboardstate.lastuseractiontime;
#if SLEEP_ACTIVE == 1
switch (keyboardstate.connectionState) {
case CONNECTION_USB:
// never sleep in this case
break;
case CONNECTION_BT:
gotoSleep(timesincelastkeypress, true);
break;
case CONNECTION_NONE:
gotoSleep(timesincelastkeypress, false);
break;
}
#endif
#if BLE_CENTRAL == 1 // this is for the master half...
if ((timesincelastkeypress < 10) && (!Bluefruit.Central.connected() && (!Bluefruit.Scanner.isRunning()))) {
Bluefruit.Scanner.start(0); // 0 = Don't stop scanning after 0 seconds ();
}
#endif
}
//********************************************************************************************//
//* Battery Monitoring Task - runs infrequently *//
//********************************************************************************************//
// TODO: move to lower priority loop. updating battery infomation isnt critical
// timers have NORMAL priorities (HIGHEST>HIGH>NORMAL>LOW>LOWEST)
// void batterytimer_callback(TimerHandle_t _handle)
//{
// batterymonitor.updateBattery();
//}
//********************************************************************************************//
//* Loop to send keypresses - moved to loop instead of timer due to delay() in processing macros *//
//********************************************************************************************//
// this loop has NORMAL priority(HIGHEST>HIGH>NORMAL>LOW>LOWEST)
// void NormalPriorityloop(void)
//{
// delay (keyboardconfig.keysendinterval);
//}
/**************************************************************************************************************************/
// put your main code here, to run repeatedly:
/**************************************************************************************************************************/
// cppcheck-suppress unusedFunction
void loop() { // has task priority TASK_PRIO_LOW
updateWDT();
speaker.processTones();
if (keyboardconfig.enableSerial) {
handleSerial();
}
switch (keyboardconfig.connectionMode) {
case CONNECTION_MODE_AUTO: // automatically switch between BLE and USB when connecting/disconnecting USB
if (usb_isConnected()) {
if (keyboardstate.connectionState != CONNECTION_USB) {
if (bt_isConnected())
bt_disconnect();
bt_stopAdv();
keyboardstate.connectionState = CONNECTION_USB;
keyboardstate.lastuseractiontime = millis(); // a USB connection will reset sleep timer...
// speaker.playTone(TONE_BLE_CONNECT);
}
} else if (bt_isConnected()) {
if (keyboardstate.connectionState != CONNECTION_BT) {
keyboardstate.connectionState = CONNECTION_BT;
keyboardstate.lastuseractiontime = millis(); // a BLE connection will reset sleep timer...
// speaker.playTone(TONE_BLE_CONNECT);
}
} else {
if (keyboardstate.connectionState != CONNECTION_NONE) {
bt_startAdv();
keyboardstate.connectionState = CONNECTION_NONE;
// speaker.playTone(TONE_BLE_DISCONNECT);
// disconnecting won't reset sleep timer.
}
}
break;
case CONNECTION_MODE_USB_ONLY:
if (usb_isConnected()) {
if (keyboardstate.connectionState != CONNECTION_USB) {
if (bt_isConnected())
bt_disconnect();
bt_stopAdv();
keyboardstate.connectionState = CONNECTION_USB;
}
} else // if USB not connected but we are in USB Mode only...
{
keyboardstate.connectionState = CONNECTION_NONE;
}
break;
case CONNECTION_MODE_BLE_ONLY:
if (bt_isConnected()) {
keyboardstate.connectionState = CONNECTION_BT;
} else {
if (keyboardstate.connectionState != CONNECTION_NONE) {
bt_startAdv();
keyboardstate.connectionState = CONNECTION_NONE;
}
}
break;
}
// TODO: check for battery filtering when switching USB in/out
// none of these things can be done in the timer event callbacks
if (keyboardstate.needUnpair) {
bt_disconnect();
char filename[32] = {0};
sprintf(filename, "/adafruit/bond_prph/%04x", keyboardconfig.BLEProfileEdiv[keyboardconfig.BLEProfile]);
InternalFS.remove(filename);
keyboardconfig.BLEProfileEdiv[keyboardconfig.BLEProfile] = 0xFFFF;
strcpy(keyboardconfig.BLEProfileName[keyboardconfig.BLEProfile], "unpaired");
keyboardstate.save2flash = true;
keyboardstate.needReset = true;
}
if (keyboardstate.save2flash) {
saveConfig();
keyboardstate.save2flash = false;
}
if (keyboardstate.needFSReset) {
InternalFS.format();
keyboardstate.needReset = true;
}
if (keyboardstate.needReset)
NVIC_SystemReset(); // this reboots the keyboard.
#ifdef WEKEY_HOST
host_progess();
#endif
#ifdef LED_MATRIX_ENABLE
is31_progess();
#endif
delay(keyboardconfig.lowpriorityloopinterval);
}; // loop is called for serials comms and saving to flash.
/**************************************************************************************************************************/
void LowestPriorityloop() { // this loop has LOWEST priority (HIGHEST>HIGH>NORMAL>LOW>LOWEST)
// it's setup to do 1 thing every call. This way, we won't take too much time from keyboard functions.
backgroundTaskID toprocess = BACKGROUND_TASK_NONE;
keyboardstate.lastuseractiontime = max(KeyScanner::getLastPressed(), keyboardstate.lastuseractiontime); // use the latest time to check for sleep...
unsigned long timesincelastkeypress = keyboardstate.timestamp - KeyScanner::getLastPressed();
updateBLEStatus();
if ((keyboardstate.timestamp - keyboardstate.batterytimer) > keyboardconfig.batteryinterval) // this is typically every 30 seconds...
{
if (timesincelastkeypress > 1000) // update if we haven't typed for 1 second
{
toprocess = BACKGROUND_TASK_BATTERY;
}
}
if ((keyboardstate.timestamp - keyboardstate.displaytimer) > 250) // update even if we type but update 4 times a second.
{ // TODO check if there is new data to display too!
toprocess = BACKGROUND_TASK_DISPLAY;
}
if ((keyboardstate.timestamp - keyboardstate.audiotimer) > 500) { // TODO: check if there is new audio to play!
toprocess = BACKGROUND_TASK_AUDIO;
}
if (keyboardconfig.enableRGBLED) {
if ((keyboardstate.timestamp - keyboardstate.rgbledtimer) > 50) {
toprocess = BACKGROUND_TASK_RGBLED;
}
}
if (keyboardconfig.enablePWMLED) {
if ((keyboardstate.timestamp - keyboardstate.pwmledtimer) > 50) {
toprocess = BACKGROUND_TASK_PWMLED;
}
}
if ((keyboardstate.timestamp - keyboardstate.statusledtimer) > 100) { // TODO: check if there is new audio to play!
toprocess = BACKGROUND_TASK_STATUSLED;
}
switch (toprocess) {
case BACKGROUND_TASK_NONE:
break;
case BACKGROUND_TASK_AUDIO:
keyboardstate.audiotimer = keyboardstate.timestamp;
break;
case BACKGROUND_TASK_BATTERY:
batterymonitor.updateBattery();
keyboardstate.batterytimer = keyboardstate.timestamp;
keyboardstate.batt_type = batterymonitor.batt_type;
keyboardstate.vbat_mv = batterymonitor.vbat_mv;
keyboardstate.vbat_per = batterymonitor.vbat_per;
keyboardstate.vbat_vdd = batterymonitor.vbat_vdd;
break;
case BACKGROUND_TASK_DISPLAY:
keyboardstate.displaytimer = keyboardstate.timestamp;
#ifdef BLUEMICRO_CONFIGURED_DISPLAY
if (keyboardconfig.enableDisplay) {
OLED.update();
} else {
OLED.sleep();
}
#endif
break;
case BACKGROUND_TASK_STATUSLED:
keyboardstate.statusledtimer = keyboardstate.timestamp;
statusLEDs.update();
break;
case BACKGROUND_TASK_PWMLED:
keyboardstate.pwmledtimer = keyboardstate.timestamp;
updatePWM(timesincelastkeypress);
break;
case BACKGROUND_TASK_RGBLED:
keyboardstate.rgbledtimer = keyboardstate.timestamp;
updateRGB(timesincelastkeypress);
break;
}
delay(keyboardconfig.lowestpriorityloopinterval); // wait not too long
}
//********************************************************************************************//
//* Idle Task - runs when there is nothing to do *//
//* Any impact of placing code here on current consumption? *//
//********************************************************************************************//
// cppcheck-suppress unusedFunction
extern "C" void vApplicationIdleHook(void) {
// Don't call any other FreeRTOS blocking API()
// Perform background task(s) here
// this task has LOWEST priority (HIGHEST>HIGH>NORMAL>LOW>LOWEST)
sd_power_mode_set(NRF_POWER_MODE_LOWPWR); // 944uA
// sd_power_mode_set(NRF_POWER_MODE_CONSTLAT); // 1.5mA
sd_app_evt_wait(); // puts the nrf52 to sleep when there is nothing to do. You need this to reduce power consumption. (removing this will increase current to
// 8mA)
};
|
; A017742: Binomial coefficients C(n,78).
; 1,79,3160,85320,1749060,29034396,406481544,4935847320,53060358690,512916800670,4513667845896,36519676207704,273897571557780,1917283000904460,12599288291657880,78115587408278856,458929076023638279,2564603660132096265,13677886187371180080,69829208430263393040,342163121308290625896,1613054714739084379224,7332066885177656269200,32197337191432316660400,136838683063587345806700,563775374221979864723604,2255101496887919458894416,8769839154564131229033840,33200105370849925367056680
add $0,78
bin $0,78
|
// --- Predefined References --
define GC_ALLOC 10001h
define HOOK 10010h
define INVOKER 10011h
define INIT_RND 10012h
define INIT_ET 10015h
define LOCK 10021h
define UNLOCK 10022h
define LOAD_CALLSTACK 10024h
define GC_HEAP_ATTRIBUTE 00Dh
procedure % INIT_RND
sub esp, 8h
mov eax, esp
sub esp, 10h
lea ebx, [esp]
push eax
push ebx
push ebx
call extern 'dlls'KERNEL32.GetSystemTime
call extern 'dlls'KERNEL32.SystemTimeToFileTime
add esp, 10h
pop eax
pop edx
ret
end
// INVOKER(prevFrame, function, arg)
procedure % INVOKER
// ; save registers
mov eax, [esp+8] // ; function
push esi
mov esi, [esp+8] // ; prevFrame
push edi
mov edi, [esp+20] // ; arg
push ecx
push ebx
push ebp
// declare new frame
push esi // ; FrameHeader.previousFrame
push 0 // ; FrameHeader.reserved
mov ebp, esp // ; FrameHeader
push edi // ; arg
call eax
add esp, 12 // ; clear FrameHeader+arg
// ; restore registers
pop ebp
pop ebx
pop ecx
pop edi
pop esi
ret
end
|
INCLUDE "./src/include/entities.inc"
INCLUDE "./src/definitions/definitions.inc"
SECTION "Enemy B", ROM0
/* Update for enemy type B
Behavior:
- Spin to win
- moves and when player on same line (x/y axis), wait for a few frames then spin after player
- when in shell/spinning mode, enemy is invulnerable to bullets
Parameters:
- hl: the starting address of the enemy
*/
UpdateEnemyB::
push hl ; PUSH HL = enemy starting address
call EnemyBounceOnWallMovement
.endDirMove
pop hl ; POP HL = enemy starting address
push hl ; PUSH HL = enemy starting address
; TODO:: might want to change animation speed when in attack mode?
; if more than ENEMY_TYPEB_ATTACK_STATE_FRAME its in attack mode, remember to offset
ld de, Character_UpdateFrameCounter
add hl, de
ld a, [hl]
add a, ENEMY_TYPEB_ANIMATION_UPDATE_SPEED
ld [hli], a
jp nc, .endUpdateEnemyB
; update frames
ld a, [hli] ; a = int part of UpdateFrameCounter
inc a
ld d, a
ld a, [hli]
ld e, a ; e = curr frame
ld a, d
.normalState ; check if player is same axis if enemy in idle state
; e = curr frame, d = int value of UpdateFrameCounter
pop hl ; POP HL = enemy starting address
push hl ; PUSH HL = enemy starting address
cp a, 1 ; check if still in idle
jr nz, .checkEnterAttackState
push de ; PUSH de = int value of UpdateFrameCounter & curr frame
ld a, [wPlayer_PosYInterpolateTarget]
and a, %11111000
ld d, a
ld a, [wPlayer_PosXInterpolateTarget]
and a, %11111000
ld e, a
inc hl
inc hl
ld a, [hli] ; get pos Y of enemy
and a, %11111000 ; 'divide' by 8, so dont need last 3 bits, convert to tile pos
ld b, a
inc hl
inc hl
ld a, [hl] ; get pos X of enemy
and a, %11111000
ld c, a
; bc = enemy tile pos, de = player tile pos, hl = pos X of enemy
ld a, b
cp a, d ; compare y axis
jr z, .playerOnSameYAxis
ld a, c
cp a, e ; compare x axis
jr z, .playerOnSameXAxis
; player not on same axis
pop de ; POP de = int value of UpdateFrameCounter & curr frame
ld d, 0 ; currFrame = 0 for normal state, reset it
jr .updateAnimationFrames
.playerOnSameYAxis ; if they are on the same y axis, check x dir, left or right. change direction
ld a, c
cp a, e ; compare x axis
jr nc, .playerLeftOfEnemy
ld d, DIR_RIGHT
jr .enemyFacePlayer
.playerLeftOfEnemy
ld d, DIR_LEFT
jr .enemyFacePlayer
.playerOnSameXAxis ; if they are on the same x axis, check y dir, up or down
ld a, b
cp a, d ; compare y axis
jr nc, .playerUpOfEnemy
ld d, DIR_DOWN
jr .enemyFacePlayer
.playerUpOfEnemy
ld d, DIR_UP
jr .enemyFacePlayer
.enemyFacePlayer ; if on same line, properly reset the position to fix to tile, x8 shift left 3 times
; bc = enemy tile pos, d = direction, hl = address of pos X
ld a, c
ld [hli], a ; init x pos
inc hl
ld a, d
ld [hl], d ; init new dir
dec hl
dec hl
dec hl
dec hl
dec hl
ld a, b
ld [hl], a ; init y pos
pop de ; POP de = int value of UpdateFrameCounter & curr frame
jr .updateAnimationFrames
.checkChargeUpState
cp a, ENEMY_TYPEB_CHARGE_ANIM_STATE_FRAME
jr nz, .checkEnterAttackState
ld e, -1 ; reset curr anim
jr .updateAnimationFrames
.checkEnterAttackState ; check if should go attack mode
cp a, ENEMY_TYPEB_ATTACK_STATE_FRAME
jr nz, .checkAttackStop
ld bc, VELOCITY_SLOW ; set the new velocity
ld e, ENEMY_TYPEB_ATTACK_ANIM_MAX_FRAMES
jr .changeVelocityAndFrames
.checkAttackStop ; check if attack should stop -> go rest mode
cp a, ENEMY_TYPEB_ATTACK_STATE_STOP_FRAME
jr nz, .updateAnimationFrames
ld d, -ENEMY_TYPEB_REST_STATE_FRAME
ld e, ENEMY_TYPEB_WALK_MAX_FRAMES
ld bc, VELOCITY_VSLOW
.changeVelocityAndFrames ; to be called when attack stop or just started
; bc = velocity, d = int value of UpdateFrameCounter, e = max frames
pop hl ; POP HL = enemy starting address
push hl ; PUSH HL = enemy starting address
push bc ; PUSH BC = temp, velocity
ld bc, Character_Velocity
add hl, bc
pop bc ; POP BC = temp, velocity
ld a, c
ld [hli], a
ld a, b
ld [hli], a ; reset velocity, store in little endian
inc hl
inc hl
inc hl
ld [hl], e ; init new max frames
ld e, -1 ; reset curr frame
.updateAnimationFrames
; e = curr frame, d = int value of UpdateFrameCounter
pop hl ; POP HL = enemy starting address
push hl ; PUSH HL = enemy starting address
ld bc, Character_UpdateFrameCounter + 1
add hl, bc
ld a, d
ld [hli], a ; store updated value for UpdateFrameCounter
inc e
inc hl
ld a, [hl] ; get max frames
cp a, e
jr nz, .continueUpdateAnimation ; check if reach max frame
ld e, 0 ; reset curr frame if reach max frame
.continueUpdateAnimation
; e = curr frame
dec hl
ld a, e
ld [hl], a
.endUpdateEnemyB
pop hl ; POP HL = enemy starting address
call InitEnemyBSprite
ret
/* Init enemy B sprite and render */
InitEnemyBSprite:
push hl
call UpdateEnemyEffects
pop hl
ld b, SCREEN_UPPER_OFFSET_Y
ld c, SCREEN_LEFT_OFFSET_X
call CheckEnemyInScreen
and a
jr z, .end
inc hl ; offset to get direction
inc hl
ld a, [hli] ; check direction of enemy and init sprite data
push af ; PUSH AF = direction
inc hl
inc hl
inc hl
inc hl ; offset to get updateFrameCounter
ld a, [hl] ; get int part of updateFrameCounter
ld d, a ; reg d = updateFrameCounter
pop af ; POP af = direction
and a, DIR_BIT_MASK
ASSERT DIR_UP == 0
and a, a ; cp a, 0
jr z, .upDir
ASSERT DIR_DOWN == 1
dec a
jr z, .downDir
ASSERT DIR_LEFT == 2
dec a
jr z, .leftDir
ASSERT DIR_RIGHT > 2
.rightDir
ld a, d ; a = updateFrameCounter
add a, ENEMY_TYPEB_REST_STATE_FRAME ; offset it
cp a, ENEMY_TYPEB_ATTACK_STATE_FRAME + ENEMY_TYPEB_REST_STATE_FRAME ; check state and init proper animation
jr nc, .leftRightDirAttack
cp a, ENEMY_TYPEB_CHARGE_ANIM_STATE_FRAME + ENEMY_TYPEB_REST_STATE_FRAME
jr c, .defaultRight
ld bc, EnemyBAnimation.hideInShellRightAnimation
jr .endDir
.defaultRight
ld bc, EnemyBAnimation.rightAnimation
jr .endDir
.upDir
ld a, d ; a = updateFrameCounter
add a, ENEMY_TYPEB_REST_STATE_FRAME ; offset it
cp a, ENEMY_TYPEB_ATTACK_STATE_FRAME + ENEMY_TYPEB_REST_STATE_FRAME; check state and init proper animation
jr nc, .upDownDirAttack
cp a, ENEMY_TYPEB_CHARGE_ANIM_STATE_FRAME + ENEMY_TYPEB_REST_STATE_FRAME
jr c, .defaultUp
ld bc, EnemyBAnimation.hideInShellUpAnimation
jr .endDir
.defaultUp
ld bc, EnemyBAnimation.upAnimation
jr .endDir
.downDir
ld a, d ; a = updateFrameCounter
add a, ENEMY_TYPEB_REST_STATE_FRAME ; offset it
cp a, ENEMY_TYPEB_ATTACK_STATE_FRAME + ENEMY_TYPEB_REST_STATE_FRAME ; check state and init proper animation
jr nc, .upDownDirAttack
cp a, ENEMY_TYPEB_CHARGE_ANIM_STATE_FRAME + ENEMY_TYPEB_REST_STATE_FRAME
jr c, .defaultDown
ld bc, EnemyBAnimation.hideInShellDownAnimation
jr .endDir
.defaultDown
ld bc, EnemyBAnimation.downAnimation
jr .endDir
.upDownDirAttack ; up and down have same attack animation
ld bc, EnemyBAnimation.attackUpAnimation
jr .endDir
.leftDir
ld a, d ; a = updateFrameCounter
add a, ENEMY_TYPEB_REST_STATE_FRAME ; offset it
cp a, ENEMY_TYPEB_ATTACK_STATE_FRAME + ENEMY_TYPEB_REST_STATE_FRAME; check state and init proper animation
jr nc, .leftRightDirAttack
cp a, ENEMY_TYPEB_CHARGE_ANIM_STATE_FRAME + ENEMY_TYPEB_REST_STATE_FRAME
jr c, .defaultLeft
ld bc, EnemyBAnimation.hideInShellLeftAnimation
jr .endDir
.defaultLeft
ld bc, EnemyBAnimation.leftAnimation
jr .endDir
.leftRightDirAttack ; right and left have same attack animation
ld bc, EnemyBAnimation.attackRightAnimation
.endDir
ld a, l
sub a, Character_UpdateFrameCounter + 1
ld l, a
ld a, h
sbc a, 0
ld h, a
call UpdateEnemySpriteOAM
.end
ret |
; A210627: Constants r_n arising in study of polynomials of least deviation from zero in several variables.
; Submitted by Christian Krause
; 72,896,14400,283392,6598144,177373184,5406289920,184223744000,6939874934784,286375842938880,12846564299505664,622448445155704832,32395710363284275200,1802446793652649852928,106760825994912064339968,6707088257932303257305088,445456559121345605093294080,31185504805980142781333504000
add $0,2
mov $1,1
add $1,$0
seq $0,214225 ; E.g.f. satisfies: A(x) = x/(1 - tanh(A(x))).
mul $0,$1
div $0,4
mul $0,8
|
; A266256: Number of ON (black) cells in the n-th iteration of the "Rule 11" elementary cellular automaton starting with a single ON (black) cell.
; 1,1,2,5,2,9,2,13,2,17,2,21,2,25,2,29,2,33,2,37,2,41,2,45,2,49,2,53,2,57,2,61,2,65,2,69,2,73,2,77,2,81,2,85,2,89,2,93,2,97,2,101,2,105,2,109,2,113,2,117,2,121,2,125,2,129,2,133,2,137,2,141,2,145,2,149,2,153,2,157,2,161,2,165,2,169,2,173,2,177,2,181,2,185,2,189,2,193,2,197,2,201,2,205,2,209,2,213,2,217,2,221,2,225,2,229,2,233,2,237,2,241,2,245,2,249,2,253,2,257,2,261,2,265,2,269,2,273,2,277,2,281,2,285,2,289,2,293,2,297,2,301,2,305,2,309,2,313,2,317,2,321,2,325,2,329,2,333,2,337,2,341,2,345,2,349,2,353,2,357,2,361,2,365,2,369,2,373,2,377,2,381,2,385,2,389,2,393,2,397,2,401,2,405,2,409,2,413,2,417,2,421,2,425,2,429,2,433,2,437,2,441,2,445,2,449,2,453,2,457,2,461,2,465,2,469,2,473,2,477,2,481,2,485,2,489,2,493,2,497
trn $0,1
mov $1,$0
mod $0,2
mul $1,2
mov $2,$0
lpb $2,1
mov $1,1
sub $2,1
lpe
add $1,1
|
#include "cpudef.asm"
; calculate telnet base address
move r5, 1
shl r5, 14
move r1, "H"
store [r5,0], r1
move r1, "e"
store [r5,0], r1
move r1, "l"
store [r5,0], r1
move r1, "l"
store [r5,0], r1
move r1, "o"
store [r5,0], r1
move r1, ","
store [r5,0], r1
move r1, " "
store [r5,0], r1
move r1, "w"
store [r5,0], r1
move r1, "o"
store [r5,0], r1
move r1, "r"
store [r5,0], r1
move r1, "l"
store [r5,0], r1
move r1, "d"
store [r5,0], r1
move r1, "!"
store [r5,0], r1
move r1, "\r"
store [r5,0], r1
move r1, "\n"
store [r5,0], r1
echo:
nop
load r1, [r5, 0]
store [r5,0], r1
nop
nop
jump echo
|
copyright zengfr site:http://github.com/zengfr/romhack
004A84 abcd -(A0), -(A2) [1p+93]
004A86 rts [1p+92]
009F9A rts [1p+92]
00A136 move.b (A7)+, ($90,A4) [1p+92]
00A2C6 dbra D0, $a2c0
copyright zengfr site:http://github.com/zengfr/romhack
|
;;
;; Copyright (c) 2012-2021, Intel Corporation
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; * Neither the name of Intel Corporation nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;
;; code to compute SHA512 by-2 using AVX
;; outer calling routine takes care of save and restore of XMM registers
;; Logic designed/laid out by JDG
;; Function clobbers: rax, rcx, rdx, rbx, rsi, rdi, r9-r15; ymm0-15
;; Stack must be aligned to 16 bytes before call
;; Windows clobbers: rax rdx r8 r9 r10 r11
;; Windows preserves: rbx rcx rsi rdi rbp r12 r13 r14 r15
;;
;; Linux clobbers: rax rsi r8 r9 r10 r11
;; Linux preserves: rbx rcx rdx rdi rbp r12 r13 r14 r15
;;
;; clobbers xmm0-15
%include "include/os.asm"
%include "include/mb_mgr_datastruct.asm"
%include "include/clear_regs.asm"
extern K512_2
section .data
default rel
align 32
; one from sha512_rorx
; this does the big endian to little endian conversion
; over a quad word
PSHUFFLE_BYTE_FLIP_MASK: ;ddq 0x08090a0b0c0d0e0f0001020304050607
dq 0x0001020304050607, 0x08090a0b0c0d0e0f
;ddq 0x18191a1b1c1d1e1f1011121314151617
dq 0x1011121314151617, 0x18191a1b1c1d1e1f
section .text
%ifdef LINUX ; Linux definitions
%define arg1 rdi
%define arg2 rsi
%else ; Windows definitions
%define arg1 rcx
%define arg2 rdx
%endif
; Common definitions
%define STATE arg1
%define INP_SIZE arg2
%define IDX rax
%define ROUND r8
%define TBL r11
%define inp0 r9
%define inp1 r10
%define a xmm0
%define b xmm1
%define c xmm2
%define d xmm3
%define e xmm4
%define f xmm5
%define g xmm6
%define h xmm7
%define a0 xmm8
%define a1 xmm9
%define a2 xmm10
%define TT0 xmm14
%define TT1 xmm13
%define TT2 xmm12
%define TT3 xmm11
%define TT4 xmm10
%define TT5 xmm9
%define T1 xmm14
%define TMP xmm15
%define SZ2 2*SHA512_DIGEST_WORD_SIZE ; Size of one vector register
%define ROUNDS 80*SZ2
; Define stack usage
struc STACK
_DATA: resb SZ2 * 16
_DIGEST: resb SZ2 * NUM_SHA512_DIGEST_WORDS
resb 8 ; for alignment, must be odd multiple of 8
endstruc
%define VMOVPD vmovupd
; transpose r0, r1, t0
; Input looks like {r0 r1}
; r0 = {a1 a0}
; r1 = {b1 b0}
;
; output looks like
; r0 = {b0, a0}
; t0 = {b1, a1}
%macro TRANSPOSE 3
%define %%r0 %1
%define %%r1 %2
%define %%t0 %3
vshufpd %%t0, %%r0, %%r1, 11b ; t0 = b1 a1
vshufpd %%r0, %%r0, %%r1, 00b ; r0 = b0 a0
%endm
%macro ROTATE_ARGS 0
%xdefine TMP_ h
%xdefine h g
%xdefine g f
%xdefine f e
%xdefine e d
%xdefine d c
%xdefine c b
%xdefine b a
%xdefine a TMP_
%endm
; PRORQ reg, imm, tmp
; packed-rotate-right-double
; does a rotate by doing two shifts and an or
%macro PRORQ 3
%define %%reg %1
%define %%imm %2
%define %%tmp %3
vpsllq %%tmp, %%reg, (64-(%%imm))
vpsrlq %%reg, %%reg, %%imm
vpor %%reg, %%reg, %%tmp
%endmacro
; non-destructive
; PRORQ_nd reg, imm, tmp, src
%macro PRORQ_nd 4
%define %%reg %1
%define %%imm %2
%define %%tmp %3
%define %%src %4
vpsllq %%tmp, %%src, (64-(%%imm))
vpsrlq %%reg, %%src, %%imm
vpor %%reg, %%reg, %%tmp
%endmacro
; PRORQ dst/src, amt
%macro PRORQ 2
PRORQ %1, %2, TMP
%endmacro
; PRORQ_nd dst, src, amt
%macro PRORQ_nd 3
PRORQ_nd %1, %3, TMP, %2
%endmacro
;; arguments passed implicitly in preprocessor symbols i, a...h
%macro ROUND_00_15 2
%define %%T1 %1
%define %%i %2
PRORQ_nd a0, e, (18-14) ; sig1: a0 = (e >> 4)
vpxor a2, f, g ; ch: a2 = f^g
vpand a2, a2, e ; ch: a2 = (f^g)&e
vpxor a2, a2, g ; a2 = ch
PRORQ_nd a1, e, 41 ; sig1: a1 = (e >> 41)
vmovdqa [SZ2*(%%i&0xf) + rsp + _DATA],%%T1
vpaddq %%T1,%%T1,[TBL + ROUND] ; T1 = W + K
vpxor a0, a0, e ; sig1: a0 = e ^ (e >> 5)
PRORQ a0, 14 ; sig1: a0 = (e >> 14) ^ (e >> 18)
vpaddq h, h, a2 ; h = h + ch
PRORQ_nd a2, a, (34-28) ; sig0: a2 = (a >> 6)
vpaddq h, h, %%T1 ; h = h + ch + W + K
vpxor a0, a0, a1 ; a0 = sigma1
vmovdqa %%T1, a ; maj: T1 = a
PRORQ_nd a1, a, 39 ; sig0: a1 = (a >> 39)
vpxor %%T1, %%T1, c ; maj: T1 = a^c
add ROUND, SZ2 ; ROUND++
vpand %%T1, %%T1, b ; maj: T1 = (a^c)&b
vpaddq h, h, a0
vpaddq d, d, h
vpxor a2, a2, a ; sig0: a2 = a ^ (a >> 11)
PRORQ a2, 28 ; sig0: a2 = (a >> 28) ^ (a >> 34)
vpxor a2, a2, a1 ; a2 = sig0
vpand a1, a, c ; maj: a1 = a&c
vpor a1, a1, %%T1 ; a1 = maj
vpaddq h, h, a1 ; h = h + ch + W + K + maj
vpaddq h, h, a2 ; h = h + ch + W + K + maj + sigma0
ROTATE_ARGS
%endm
;; arguments passed implicitly in preprocessor symbols i, a...h
%macro ROUND_16_XX 2
%define %%T1 %1
%define %%i %2
vmovdqa %%T1, [SZ2*((%%i-15)&0xf) + rsp + _DATA]
vmovdqa a1, [SZ2*((%%i-2)&0xf) + rsp + _DATA]
vmovdqa a0, %%T1
PRORQ %%T1, 8-1
vmovdqa a2, a1
PRORQ a1, 61-19
vpxor %%T1, %%T1, a0
PRORQ %%T1, 1
vpxor a1, a1, a2
PRORQ a1, 19
vpsrlq a0, a0, 7
vpxor %%T1, %%T1, a0
vpsrlq a2, a2, 6
vpxor a1, a1, a2
vpaddq %%T1, %%T1, [SZ2*((%%i-16)&0xf) + rsp + _DATA]
vpaddq a1, a1, [SZ2*((%%i-7)&0xf) + rsp + _DATA]
vpaddq %%T1, %%T1, a1
ROUND_00_15 %%T1, %%i
%endm
;; SHA512_ARGS:
;; UINT128 digest[8]; // transposed digests
;; UINT8 *data_ptr[2];
;;
;; void sha512_x2_avx(SHA512_ARGS *args, UINT64 msg_size_in_blocks)
;; arg 1 : STATE : pointer args
;; arg 2 : INP_SIZE : size of data in blocks (assumed >= 1)
;;
MKGLOBAL(sha512_x2_avx,function,internal)
align 32
sha512_x2_avx:
; general registers preserved in outer calling routine
; outer calling routine saves all the XMM registers
sub rsp, STACK_size
;; Load the pre-transposed incoming digest.
vmovdqa a,[STATE + 0 * SHA512_DIGEST_ROW_SIZE]
vmovdqa b,[STATE + 1 * SHA512_DIGEST_ROW_SIZE]
vmovdqa c,[STATE + 2 * SHA512_DIGEST_ROW_SIZE]
vmovdqa d,[STATE + 3 * SHA512_DIGEST_ROW_SIZE]
vmovdqa e,[STATE + 4 * SHA512_DIGEST_ROW_SIZE]
vmovdqa f,[STATE + 5 * SHA512_DIGEST_ROW_SIZE]
vmovdqa g,[STATE + 6 * SHA512_DIGEST_ROW_SIZE]
vmovdqa h,[STATE + 7 * SHA512_DIGEST_ROW_SIZE]
lea TBL,[rel K512_2]
;; load the address of each of the 2 message lanes
;; getting ready to transpose input onto stack
mov inp0,[STATE + _data_ptr_sha512 +0*PTR_SZ]
mov inp1,[STATE + _data_ptr_sha512 +1*PTR_SZ]
xor IDX, IDX
lloop:
xor ROUND, ROUND
;; save old digest
vmovdqa [rsp + _DIGEST + 0*SZ2], a
vmovdqa [rsp + _DIGEST + 1*SZ2], b
vmovdqa [rsp + _DIGEST + 2*SZ2], c
vmovdqa [rsp + _DIGEST + 3*SZ2], d
vmovdqa [rsp + _DIGEST + 4*SZ2], e
vmovdqa [rsp + _DIGEST + 5*SZ2], f
vmovdqa [rsp + _DIGEST + 6*SZ2], g
vmovdqa [rsp + _DIGEST + 7*SZ2], h
%assign i 0
%rep 8
;; load up the shuffler for little-endian to big-endian format
vmovdqa TMP, [rel PSHUFFLE_BYTE_FLIP_MASK]
VMOVPD TT0,[inp0+IDX+i*16] ;; double precision is 64 bits
VMOVPD TT2,[inp1+IDX+i*16]
TRANSPOSE TT0, TT2, TT1
vpshufb TT0, TT0, TMP
vpshufb TT1, TT1, TMP
ROUND_00_15 TT0,(i*2+0)
ROUND_00_15 TT1,(i*2+1)
%assign i (i+1)
%endrep
;; Increment IDX by message block size == 8 (loop) * 16 (XMM width in bytes)
add IDX, 8 * 16
%assign i (i*4)
jmp Lrounds_16_xx
align 16
Lrounds_16_xx:
%rep 16
ROUND_16_XX T1, i
%assign i (i+1)
%endrep
cmp ROUND,ROUNDS
jb Lrounds_16_xx
;; add old digest
vpaddq a, a, [rsp + _DIGEST + 0*SZ2]
vpaddq b, b, [rsp + _DIGEST + 1*SZ2]
vpaddq c, c, [rsp + _DIGEST + 2*SZ2]
vpaddq d, d, [rsp + _DIGEST + 3*SZ2]
vpaddq e, e, [rsp + _DIGEST + 4*SZ2]
vpaddq f, f, [rsp + _DIGEST + 5*SZ2]
vpaddq g, g, [rsp + _DIGEST + 6*SZ2]
vpaddq h, h, [rsp + _DIGEST + 7*SZ2]
sub INP_SIZE, 1 ;; consumed one message block
jne lloop
; write back to memory (state object) the transposed digest
vmovdqa [STATE+0*SHA512_DIGEST_ROW_SIZE],a
vmovdqa [STATE+1*SHA512_DIGEST_ROW_SIZE],b
vmovdqa [STATE+2*SHA512_DIGEST_ROW_SIZE],c
vmovdqa [STATE+3*SHA512_DIGEST_ROW_SIZE],d
vmovdqa [STATE+4*SHA512_DIGEST_ROW_SIZE],e
vmovdqa [STATE+5*SHA512_DIGEST_ROW_SIZE],f
vmovdqa [STATE+6*SHA512_DIGEST_ROW_SIZE],g
vmovdqa [STATE+7*SHA512_DIGEST_ROW_SIZE],h
; update input pointers
add inp0, IDX
mov [STATE + _data_ptr_sha512 + 0*PTR_SZ], inp0
add inp1, IDX
mov [STATE + _data_ptr_sha512 + 1*PTR_SZ], inp1
;;;;;;;;;;;;;;;;
;; Postamble
;; Clear stack frame ((16 + 8)*16 bytes)
%ifdef SAFE_DATA
clear_all_xmms_avx_asm
%assign i 0
%rep (16+NUM_SHA512_DIGEST_WORDS)
vmovdqa [rsp + i*SZ2], xmm0
%assign i (i+1)
%endrep
%endif
add rsp, STACK_size
; outer calling routine restores XMM and other GP registers
ret
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/connect_job.h"
#include <utility>
#include "base/trace_event/trace_event.h"
#include "net/base/net_errors.h"
#include "net/base/trace_constants.h"
#include "net/http/http_auth_controller.h"
#include "net/http/http_proxy_connect_job.h"
#include "net/log/net_log.h"
#include "net/log/net_log_event_type.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/socket_tag.h"
#include "net/socket/socks_connect_job.h"
#include "net/socket/ssl_connect_job.h"
#include "net/socket/stream_socket.h"
#include "net/socket/transport_connect_job.h"
#include "net/ssl/ssl_config.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
namespace net {
CommonConnectJobParams::CommonConnectJobParams(
ClientSocketFactory* client_socket_factory,
HostResolver* host_resolver,
HttpAuthCache* http_auth_cache,
HttpAuthHandlerFactory* http_auth_handler_factory,
SpdySessionPool* spdy_session_pool,
const quic::ParsedQuicVersionVector* quic_supported_versions,
QuicStreamFactory* quic_stream_factory,
ProxyDelegate* proxy_delegate,
const HttpUserAgentSettings* http_user_agent_settings,
SSLClientContext* ssl_client_context,
SocketPerformanceWatcherFactory* socket_performance_watcher_factory,
NetworkQualityEstimator* network_quality_estimator,
NetLog* net_log,
WebSocketEndpointLockManager* websocket_endpoint_lock_manager)
: client_socket_factory(client_socket_factory),
host_resolver(host_resolver),
http_auth_cache(http_auth_cache),
http_auth_handler_factory(http_auth_handler_factory),
spdy_session_pool(spdy_session_pool),
quic_supported_versions(quic_supported_versions),
quic_stream_factory(quic_stream_factory),
proxy_delegate(proxy_delegate),
http_user_agent_settings(http_user_agent_settings),
ssl_client_context(ssl_client_context),
socket_performance_watcher_factory(socket_performance_watcher_factory),
network_quality_estimator(network_quality_estimator),
net_log(net_log),
websocket_endpoint_lock_manager(websocket_endpoint_lock_manager) {}
CommonConnectJobParams::CommonConnectJobParams(
const CommonConnectJobParams& other) = default;
CommonConnectJobParams::~CommonConnectJobParams() = default;
CommonConnectJobParams& CommonConnectJobParams::operator=(
const CommonConnectJobParams& other) = default;
ConnectJob::ConnectJob(RequestPriority priority,
const SocketTag& socket_tag,
base::TimeDelta timeout_duration,
const CommonConnectJobParams* common_connect_job_params,
Delegate* delegate,
const NetLogWithSource* net_log,
NetLogSourceType net_log_source_type,
NetLogEventType net_log_connect_event_type)
: timeout_duration_(timeout_duration),
priority_(priority),
socket_tag_(socket_tag),
common_connect_job_params_(common_connect_job_params),
delegate_(delegate),
top_level_job_(net_log == nullptr),
net_log_(net_log
? *net_log
: NetLogWithSource::Make(common_connect_job_params->net_log,
net_log_source_type)),
net_log_connect_event_type_(net_log_connect_event_type) {
DCHECK(delegate);
if (top_level_job_)
net_log_.BeginEvent(NetLogEventType::CONNECT_JOB);
}
ConnectJob::~ConnectJob() {
// Log end of Connect event if ConnectJob was still in-progress when
// destroyed.
if (delegate_)
LogConnectCompletion(ERR_ABORTED);
if (top_level_job_)
net_log().EndEvent(NetLogEventType::CONNECT_JOB);
}
std::unique_ptr<ConnectJob> ConnectJob::CreateConnectJob(
bool using_ssl,
const HostPortPair& endpoint,
const ProxyServer& proxy_server,
const base::Optional<NetworkTrafficAnnotationTag>& proxy_annotation_tag,
const SSLConfig* ssl_config_for_origin,
const SSLConfig* ssl_config_for_proxy,
bool force_tunnel,
PrivacyMode privacy_mode,
const OnHostResolutionCallback& resolution_callback,
RequestPriority request_priority,
SocketTag socket_tag,
const NetworkIsolationKey& network_isolation_key,
bool disable_secure_dns,
const CommonConnectJobParams* common_connect_job_params,
ConnectJob::Delegate* delegate) {
scoped_refptr<HttpProxySocketParams> http_proxy_params;
scoped_refptr<SOCKSSocketParams> socks_params;
if (!proxy_server.is_direct()) {
// No need to use a NetworkIsolationKey for looking up the proxy's IP
// address. Cached proxy IP addresses doesn't really expose useful
// information to destination sites, and not caching them has a performance
// cost.
auto proxy_tcp_params = base::MakeRefCounted<TransportSocketParams>(
proxy_server.host_port_pair(), NetworkIsolationKey(),
disable_secure_dns, resolution_callback);
if (proxy_server.is_http_like()) {
scoped_refptr<SSLSocketParams> ssl_params;
if (proxy_server.is_secure_http_like()) {
DCHECK(ssl_config_for_proxy);
// Set ssl_params, and unset proxy_tcp_params
ssl_params = base::MakeRefCounted<SSLSocketParams>(
std::move(proxy_tcp_params), nullptr, nullptr,
proxy_server.host_port_pair(), *ssl_config_for_proxy,
PRIVACY_MODE_DISABLED, network_isolation_key);
proxy_tcp_params = nullptr;
}
http_proxy_params = base::MakeRefCounted<HttpProxySocketParams>(
std::move(proxy_tcp_params), std::move(ssl_params),
proxy_server.is_quic(), endpoint, proxy_server.is_trusted_proxy(),
force_tunnel || using_ssl, *proxy_annotation_tag,
network_isolation_key);
} else {
DCHECK(proxy_server.is_socks());
socks_params = base::MakeRefCounted<SOCKSSocketParams>(
std::move(proxy_tcp_params),
proxy_server.scheme() == ProxyServer::SCHEME_SOCKS5, endpoint,
network_isolation_key, *proxy_annotation_tag);
}
}
// Deal with SSL - which layers on top of any given proxy.
if (using_ssl) {
DCHECK(ssl_config_for_origin);
scoped_refptr<TransportSocketParams> ssl_tcp_params;
if (proxy_server.is_direct()) {
ssl_tcp_params = base::MakeRefCounted<TransportSocketParams>(
endpoint, network_isolation_key, disable_secure_dns,
resolution_callback);
}
auto ssl_params = base::MakeRefCounted<SSLSocketParams>(
std::move(ssl_tcp_params), std::move(socks_params),
std::move(http_proxy_params), endpoint, *ssl_config_for_origin,
privacy_mode, network_isolation_key);
return std::make_unique<SSLConnectJob>(
request_priority, socket_tag, common_connect_job_params,
std::move(ssl_params), delegate, nullptr /* net_log */);
}
if (proxy_server.is_http_like()) {
return std::make_unique<HttpProxyConnectJob>(
request_priority, socket_tag, common_connect_job_params,
std::move(http_proxy_params), delegate, nullptr /* net_log */);
}
if (proxy_server.is_socks()) {
return std::make_unique<SOCKSConnectJob>(
request_priority, socket_tag, common_connect_job_params,
std::move(socks_params), delegate, nullptr /* net_log */);
}
DCHECK(proxy_server.is_direct());
auto tcp_params = base::MakeRefCounted<TransportSocketParams>(
endpoint, network_isolation_key, disable_secure_dns, resolution_callback);
return TransportConnectJob::CreateTransportConnectJob(
std::move(tcp_params), request_priority, socket_tag,
common_connect_job_params, delegate, nullptr /* net_log */);
}
std::unique_ptr<StreamSocket> ConnectJob::PassSocket() {
return std::move(socket_);
}
void ConnectJob::ChangePriority(RequestPriority priority) {
priority_ = priority;
ChangePriorityInternal(priority);
}
int ConnectJob::Connect() {
if (!timeout_duration_.is_zero())
timer_.Start(FROM_HERE, timeout_duration_, this, &ConnectJob::OnTimeout);
LogConnectStart();
int rv = ConnectInternal();
if (rv != ERR_IO_PENDING) {
LogConnectCompletion(rv);
delegate_ = nullptr;
}
return rv;
}
ConnectionAttempts ConnectJob::GetConnectionAttempts() const {
// Return empty list by default - used by proxy classes.
return ConnectionAttempts();
}
bool ConnectJob::IsSSLError() const {
return false;
}
scoped_refptr<SSLCertRequestInfo> ConnectJob::GetCertRequestInfo() {
return nullptr;
}
void ConnectJob::SetSocket(std::unique_ptr<StreamSocket> socket) {
if (socket)
net_log().AddEvent(NetLogEventType::CONNECT_JOB_SET_SOCKET);
socket_ = std::move(socket);
}
void ConnectJob::NotifyDelegateOfCompletion(int rv) {
TRACE_EVENT0(NetTracingCategory(), "ConnectJob::NotifyDelegateOfCompletion");
// The delegate will own |this|.
Delegate* delegate = delegate_;
delegate_ = nullptr;
LogConnectCompletion(rv);
delegate->OnConnectJobComplete(rv, this);
}
void ConnectJob::NotifyDelegateOfProxyAuth(
const HttpResponseInfo& response,
HttpAuthController* auth_controller,
base::OnceClosure restart_with_auth_callback) {
delegate_->OnNeedsProxyAuth(response, auth_controller,
std::move(restart_with_auth_callback), this);
}
void ConnectJob::ResetTimer(base::TimeDelta remaining_time) {
timer_.Stop();
if (!remaining_time.is_zero())
timer_.Start(FROM_HERE, remaining_time, this, &ConnectJob::OnTimeout);
}
bool ConnectJob::TimerIsRunning() const {
return timer_.IsRunning();
}
void ConnectJob::LogConnectStart() {
connect_timing_.connect_start = base::TimeTicks::Now();
net_log().BeginEvent(net_log_connect_event_type_);
}
void ConnectJob::LogConnectCompletion(int net_error) {
connect_timing_.connect_end = base::TimeTicks::Now();
net_log().EndEventWithNetErrorCode(net_log_connect_event_type_, net_error);
}
void ConnectJob::OnTimeout() {
// Make sure the socket is NULL before calling into |delegate|.
SetSocket(nullptr);
OnTimedOutInternal();
net_log_.AddEvent(NetLogEventType::CONNECT_JOB_TIMED_OUT);
NotifyDelegateOfCompletion(ERR_TIMED_OUT);
}
void ConnectJob::OnTimedOutInternal() {}
} // namespace net
|
/*******************************************************************************
* Copyright 2019-2020 Intel Corporation
*
* 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.
*******************************************************************************/
#ifndef GPU_OCL_CROSS_ENGINE_REORDER_HPP
#define GPU_OCL_CROSS_ENGINE_REORDER_HPP
#include "common/c_types_map.hpp"
#include "common/memory.hpp"
#include "common/primitive.hpp"
#include "common/utils.hpp"
#include "gpu/gpu_primitive.hpp"
#include "gpu/gpu_reorder_pd.hpp"
#include "gpu/ocl/ocl_utils.hpp"
namespace dnnl {
namespace impl {
namespace gpu {
namespace ocl {
// Cross-engine reorder manages all reorders between GPU and CPU engines.
//
// For CPU -> GPU reorder, it includes 2 steps:
// 1. CPU -> GPU copying
// 2. GPU reorder
//
// For GPU -> CPU reorder, it includes 2 steps:
// 1. GPU reorder
// 2. GPU -> CPU copying
struct cross_engine_reorder_t : public gpu_primitive_t {
struct pd_t : public reorder_pd_t {
using reorder_pd_t::reorder_pd_t;
pd_t(const pd_t &rhs)
: reorder_pd_t(rhs)
, reorder_pd_(rhs.do_reorder_ ? rhs.reorder_pd_->clone() : nullptr)
, reorder_engine_kind_(rhs.reorder_engine_kind_)
, do_reorder_(rhs.do_reorder_) {}
DECLARE_COMMON_PD_T("ocl:cross_engine::any", cross_engine_reorder_t);
DECLARE_GPU_REORDER_CREATE();
status_t init(
engine_t *engine, engine_t *src_engine, engine_t *dst_engine);
std::unique_ptr<primitive_desc_t> reorder_pd_;
engine_kind_t reorder_engine_kind_ = engine_kind::gpu;
bool do_reorder_ = true;
private:
void init_scratchpad();
};
cross_engine_reorder_t(const pd_t *apd) : gpu_primitive_t(apd) {}
status_t init(engine_t *engine) override {
if (!pd()->do_reorder_) return status::success;
auto status = pd()->reorder_pd_->create_primitive(reorder_, engine);
return status;
}
status_t execute(const exec_ctx_t &ctx) const override;
protected:
primitive_list_t nested_primitives() const override {
return {reorder_.get()};
}
private:
const pd_t *pd() const { return (const pd_t *)primitive_t::pd().get(); }
std::shared_ptr<primitive_t> reorder_;
};
} // namespace ocl
} // namespace gpu
} // namespace impl
} // namespace dnnl
#endif
|
; A129818: Riordan array (1/(1+x), x/(1+x)^2), inverse array is A039599.
; Submitted by Jon Maiga
; 1,-1,1,1,-3,1,-1,6,-5,1,1,-10,15,-7,1,-1,15,-35,28,-9,1,1,-21,70,-84,45,-11,1,-1,28,-126,210,-165,66,-13,1,1,-36,210,-462,495,-286,91,-15,1,-1,45,-330,924,-1287,1001,-455,120,-17,1,1,-55,495,-1716,3003,-3003,1820,-680,153,-19,1,-1,66,-715,3003,-6435,8008,-6188,3060,-969,190,-21,1,1,-78,1001,-5005,12870,-19448,18564,-11628,4845,-1330,231,-23,1,-1,91,-1365,8008,-24310,43758,-50388,38760,-20349
lpb $0
add $1,1
sub $0,$1
lpe
sub $0,$1
mul $0,-1
mul $1,2
sub $1,$0
mul $1,-1
sub $1,1
add $1,$0
bin $1,$0
mov $0,$1
|
; A154388: Triangle T(n,k), 0<=k<=n, read by rows given by [0,1,-1,0,0,0,0,0,0,0,...] DELTA [1,-1,-1,1,0,0,0,0,0,0,0,...] where DELTA is the operator defined in A084938.
; 1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0
mov $2,$0
mov $3,2
lpb $0
mov $0,0
seq $1,100285 ; Expansion of (1+5x^2)/(1-x+x^2-x^3).
lpe
lpb $3
mov $0,$2
sub $3,1
add $0,$3
add $0,1
seq $0,130855 ; 2n appears 2n+1 times, 2n+1 appears 2n times.
sub $1,$0
lpe
sub $1,1
mod $1,2
add $1,2
mod $1,2
mov $0,$1
|
//$Id: Solver.cpp 11403 2013-02-28 00:08:36Z djcinsb $
//------------------------------------------------------------------------------
// Solver
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002-2011 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG04CC06P
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: 2003/12/29
//
/**
* Base class for Targeters, Optimizers, and other parametric scanning tools.
*/
//------------------------------------------------------------------------------
#include <sstream>
#include "Solver.hpp"
#include "MessageInterface.hpp"
#include "FileManager.hpp"
#include "OwnedPlot.hpp" // Replace with a proxy
//#define DEBUG_SOLVER_INIT
//#define DEBUG_SOLVER_CALC
//#define DEBUG_STATE_MACHINE
//---------------------------------
// static data
//---------------------------------
const std::string
Solver::PARAMETER_TEXT[SolverParamCount - GmatBaseParamCount] =
{
"ShowProgress",
"ReportStyle",
"ReportFile",
"Variables",
"MaximumIterations",
"NumberOfVariables",
"RegisteredVariables",
"RegisteredComponents",
"AllowScaleSetting",
"AllowRangeSettings",
"AllowStepsizeSetting",
"AllowVariablePertSetting",
"SolverMode",
"ExitMode",
"SolverStatus"
};
const Gmat::ParameterType
Solver::PARAMETER_TYPE[SolverParamCount - GmatBaseParamCount] =
{
Gmat::BOOLEAN_TYPE,
Gmat::ENUMERATION_TYPE,
Gmat::FILENAME_TYPE,
Gmat::STRINGARRAY_TYPE,
Gmat::INTEGER_TYPE,
Gmat::INTEGER_TYPE,
Gmat::INTEGER_TYPE,
Gmat::INTEGER_TYPE,
Gmat::BOOLEAN_TYPE,
Gmat::BOOLEAN_TYPE,
Gmat::BOOLEAN_TYPE,
Gmat::BOOLEAN_TYPE,
Gmat::STRING_TYPE,
Gmat::STRING_TYPE,
Gmat::INTEGER_TYPE
};
const std::string
Solver::STYLE_TEXT[MaxStyle - NORMAL_STYLE] =
{
"Normal",
"Concise",
"Verbose",
"Debug"
};
//---------------------------------
// public methods
//---------------------------------
//------------------------------------------------------------------------------
// Solver(const std::string &type, const std::string &name)
//------------------------------------------------------------------------------
/**
* Core constructor for Solver objects.
*
* @param type Text description of the type of solver constructed
* (e.g. "DifferentialCorrector")
* @param name The solver's name
*/
//------------------------------------------------------------------------------
Solver::Solver(const std::string &type, const std::string &name) :
GmatBase (Gmat::SOLVER, type, name),
isInternal (true),
currentState (INITIALIZING),
nestedState (INITIALIZING),
textFileMode ("Normal"),
showProgress (true),
progressStyle (NORMAL_STYLE),
debugString (""),
variableCount (0),
//variable (NULL),
iterationsTaken (0),
maxIterations (25),
//perturbation (NULL),
//variableMinimum (NULL),
//variableMaximum (NULL),
//variableMaximumStep (NULL),
pertNumber (-999), // is this right?
instanceNumber (0), // 0 indicates 1st instance w/ this name
registeredVariableCount (0),
registeredComponentCount(0),
AllowScaleFactors (true),
AllowRangeLimits (true),
AllowStepsizeLimit (true),
AllowIndependentPerts (true),
solverMode (""),
currentMode (SOLVE),
exitMode (DISCARD),
status (CREATED),
plotCount (0),
plotter (NULL),
hasFired (false)
{
objectTypes.push_back(Gmat::SOLVER);
objectTypeNames.push_back("Solver");
//solverTextFile = "solver_";
solverTextFile = type;
solverTextFile += instanceName;
solverTextFile += ".data";
}
//------------------------------------------------------------------------------
// Solver(std::string type, std::string name)
//------------------------------------------------------------------------------
/**
* Solver destructor.
*/
//------------------------------------------------------------------------------
Solver::~Solver()
{
if (textFile.is_open())
textFile.close();
if (plotter != NULL)
delete plotter;
}
//------------------------------------------------------------------------------
// Solver(const Solver &sol)
//------------------------------------------------------------------------------
/**
* Copy constructor for Solver objects.
*
* @param sol The solver that is copied
*/
//------------------------------------------------------------------------------
Solver::Solver(const Solver &sol) :
GmatBase (sol),
isInternal (sol.isInternal),
currentState (sol.currentState),
nestedState (sol.currentState),
textFileMode (sol.textFileMode),
showProgress (sol.showProgress),
progressStyle (sol.progressStyle),
debugString (sol.debugString),
variableCount (sol.variableCount),
//variable (NULL),
iterationsTaken (0),
maxIterations (sol.maxIterations),
//perturbation (NULL),
//variableMinimum (NULL),
//variableMaximum (NULL),
//variableMaximumStep (NULL),
pertNumber (sol.pertNumber),
solverTextFile (sol.solverTextFile),
instanceNumber (sol.instanceNumber),
registeredVariableCount (sol.registeredVariableCount),
registeredComponentCount(sol.registeredComponentCount),
AllowScaleFactors (sol.AllowScaleFactors),
AllowRangeLimits (sol.AllowRangeLimits),
AllowStepsizeLimit (sol.AllowStepsizeLimit),
AllowIndependentPerts (sol.AllowIndependentPerts),
solverMode (sol.solverMode),
currentMode (sol.currentMode),
exitMode (sol.exitMode),
status (CREATED),
plotCount (sol.plotCount),
plotter (NULL),
hasFired (false)
{
#ifdef DEBUG_SOLVER_INIT
MessageInterface::ShowMessage(
"In Solver::Solver (copy constructor)\n");
#endif
variableNames.clear();
//variable.clear();
//perturbation.clear();
//variableMinimum.clear();
//variableMaximum.clear();
//variableMaximumStep.clear();
isInitialized = false;
}
//------------------------------------------------------------------------------
// Solver& operator=(const Solver &sol)
//------------------------------------------------------------------------------
/**
* Assignment operator for solvers
*
* @return this Solver, set to the same parameters as the input solver.
*/
//------------------------------------------------------------------------------
Solver& Solver::operator=(const Solver &sol)
{
if (&sol == this)
return *this;
GmatBase::operator=(sol);
registeredVariableCount = sol.registeredVariableCount;
registeredComponentCount = sol.registeredComponentCount;
variableCount = sol.variableCount;
iterationsTaken = 0;
maxIterations = sol.maxIterations;
isInitialized = false;
solverTextFile = sol.solverTextFile;
variableNames.clear();
//variable.clear();
//perturbation.clear();
//variableMinimum.clear();
//variableMaximum.clear();
//variableMaximumStep.clear();
currentState = sol.currentState;
nestedState = sol.currentState;
textFileMode = sol.textFileMode;
showProgress = sol.showProgress;
progressStyle = sol.progressStyle;
debugString = sol.debugString;
instanceNumber = sol.instanceNumber;
pertNumber = sol.pertNumber;
solverMode = sol.solverMode;
currentMode = sol.currentMode;
exitMode = sol.exitMode;
status = COPIED;
plotCount = sol.plotCount;
plotter = NULL;
hasFired = false;
AllowScaleFactors = sol. AllowScaleFactors;
AllowRangeLimits = sol.AllowRangeLimits;
AllowStepsizeLimit = sol.AllowStepsizeLimit;
AllowIndependentPerts = sol.AllowIndependentPerts;
return *this;
}
//------------------------------------------------------------------------------
// bool Initialize()
//------------------------------------------------------------------------------
/**
* Derived classes implement this method to set object pointers and validate
* internal data structures.
*
* @return true on success, false (or throws a SolverException) on failure
*/
//------------------------------------------------------------------------------
bool Solver::Initialize()
{
// Setup the variable data structures
Integer localVariableCount = variableNames.size();
#ifdef DEBUG_SOLVER_INIT
MessageInterface::ShowMessage(
"In Solver::Initialize with localVariableCount = %d\n",
localVariableCount);
#endif
try
{
#ifdef DEBUG_SOLVER_INIT
MessageInterface::ShowMessage(
"In Solver::Initialize - about to set default values\n");
#endif
for (Integer i = 0; i < localVariableCount; ++i)
{
variable.push_back(0.0);
variableInitialValues.push_back(0.0);
variableMinimum.push_back(-9.999e300);
variableMaximum.push_back(9.999e300);
variableMaximumStep.push_back(9.999e300);
perturbation.push_back(1.0e-04);
pertDirection.push_back(1.0);
unscaledVariable.push_back(0.0);
}
}
catch(const std::exception &)
{
throw SolverException("Range error initializing Solver object %s\n",
instanceName.c_str());
}
isInitialized = true;
iterationsTaken = 0;
#ifdef DEBUG_SOLVER_INIT
MessageInterface::ShowMessage(
"In Solver::Initialize completed\n");
#endif
status = INITIALIZED;
// if (plotter)
// delete plotter;
// if (plotCount > 0)
// {
// plotter = new OwnedPlot("");
// plotter->SetName(instanceName + "_masterPlot");
// }
return true;
}
bool Solver::Finalize()
{
// Close the solver text file
if (textFile.is_open())
{
textFile.flush();
textFile.close();
}
return true;
}
//------------------------------------------------------------------------------
// Integer SetSolverVariables(Real *data, const std::string &name)
//------------------------------------------------------------------------------
/**
* Derived classes use this method to pass in parameter data specific to
* the algorithm implemented.
*
* @param <data> An array of data appropriate to the variables used in the
* algorithm.
* @param <name> A label for the data parameter. Defaults to the empty
* string.
*
* @return The ID used for the variable.
*/
//------------------------------------------------------------------------------
Integer Solver::SetSolverVariables(Real *data, const std::string &name)
{
if (variableNames[variableCount] != name)
throw SolverException("Mismatch between parsed and configured variable");
//variable[variableCount] = data[0];
//perturbation[variableCount] = data[1];
try
{
variable.at(variableCount) = data[0];
variableInitialValues.at(variableCount) = data[0];
perturbation.at(variableCount) = data[1];
}
catch(const std::exception &)
{
throw SolverException(
"Range error setting variable or perturbation in "
"SetSolverVariables\n");
}
// Sanity check min and max
if (data[2] >= data[3])
{
std::stringstream errMsg;
errMsg << "Minimum allowed variable value (received " << data[2]
<< ") must be less than maximum (received " << data[3] << ")";
throw SolverException(errMsg.str());
}
if (data[4] <= 0.0)
{
std::stringstream errMsg;
errMsg << "Largest allowed step must be positive! (received "
<< data[4] << ")";
throw SolverException(errMsg.str());
}
//variableMinimum[variableCount] = data[2];
//variableMaximum[variableCount] = data[3];
//variableMaximumStep[variableCount] = data[4];
try
{
variableMinimum.at(variableCount) = data[2];
variableMaximum.at(variableCount) = data[3];
variableMaximumStep.at(variableCount) = data[4];
unscaledVariable.at(variableCount) = data[5];
}
catch(const std::exception &)
{
throw SolverException(
"Range error setting variable min/max in SetSolverVariables\n");
}
++variableCount;
return variableCount-1;
}
//------------------------------------------------------------------------------
// bool Solver::RefreshSolverVariables(Real *data, const std::string &name)
//------------------------------------------------------------------------------
/**
* Refreshes Variable data to the current Mission Control Sequence values.
*
* Updates the solver's variable parameters for elements that change as the
* result of previous commands -- for instance, Variable updates in a script,
* where the Variable is used to set a parameter on the Solver's variable data.
*
* @param <data> An array of data appropriate to the variables used in the
* algorithm.
* @param <name> A label for the data parameter.
*
* @return true is the data was updated, false if not.
*/
//------------------------------------------------------------------------------
bool Solver::RefreshSolverVariables(Real *data, const std::string &name)
{
bool retval = false;
if (hasFired && (exitMode == RETAIN))
return true;
#ifdef DEBUG_SAVEANDCONTINUE
MessageInterface::ShowMessage("Resetting variables for %s\n",
instanceName.c_str());
#endif
// Find index of the variable
for (UnsignedInt n = 0; n < variableNames.size(); ++n)
{
std::string varName = variableNames[n];
if (varName == name)
{
try
{
variable.at(n) = data[0];
variableInitialValues.at(n) = data[0];
perturbation.at(n) = data[1];
}
catch(const std::exception &)
{
throw SolverException(
"Range error setting variable or perturbation in "
"SetSolverVariables\n");
}
// Sanity check min and max
if (data[2] >= data[3])
{
std::stringstream errMsg;
errMsg << "Minimum allowed variable value (received " << data[2]
<< ") must be less than maximum (received " << data[3] << ")";
throw SolverException(errMsg.str());
}
if (data[4] <= 0.0)
{
std::stringstream errMsg;
errMsg << "Largest allowed step must be positive! (received "
<< data[4] << ")";
throw SolverException(errMsg.str());
}
//variableMinimum[variableCount] = data[2];
//variableMaximum[variableCount] = data[3];
//variableMaximumStep[variableCount] = data[4];
try
{
variableMinimum.at(n) = data[2];
variableMaximum.at(n) = data[3];
variableMaximumStep.at(n) = data[4];
unscaledVariable.at(n) = data[5];
}
catch(const std::exception &)
{
throw SolverException(
"Range error setting variable min/max in "
"RefreshSolverVariables\n");
}
retval = true;
}
}
return retval;
}
//------------------------------------------------------------------------------
// Real GetSolverVariable(Integer id)
//------------------------------------------------------------------------------
/**
* Interface used to access Variable values.
*
* @param <id> The ID used for the variable.
*
* @return The value used for this variable
*/
//------------------------------------------------------------------------------
Real Solver::GetSolverVariable(Integer id)
{
if (id >= variableCount)
throw SolverException(
"Solver member requested a parameter outside the range "
"of the configured variables.");
#ifdef DEBUG_STATE_MACHINE
MessageInterface::ShowMessage(
" State %d setting variable %d to value = %.12lf\n",
currentState, id, variable.at(id));
#endif
return variable.at(id);
}
//------------------------------------------------------------------------------
// void SetUnscaledVariable(Integer id, Real value)
//------------------------------------------------------------------------------
/**
* Sets the unscaled value of variables for reporting purposes
*
* @param id The ID of the variable
* @param value The unscaled value
*/
//------------------------------------------------------------------------------
void Solver::SetUnscaledVariable(Integer id, Real value)
{
if (id >= variableCount)
throw SolverException(
"Solver member requested a parameter outside the range "
"of the configured variables.");
unscaledVariable.at(id) = value;
}
//------------------------------------------------------------------------------
// SolverState GetState()
//------------------------------------------------------------------------------
/**
* Determine the state-machine state of this instance of the Solver.
*
* @return current state
*/
//------------------------------------------------------------------------------
Solver::SolverState Solver::GetState()
{
return currentState;
}
//------------------------------------------------------------------------------
// SolverState GetNestedState()
//------------------------------------------------------------------------------
/**
* Determine the state-machine nested state of this instance of the Solver.
*
* @return nested State
*/
//------------------------------------------------------------------------------
Solver::SolverState Solver::GetNestedState()
{
return nestedState;
}
//------------------------------------------------------------------------------
// Solver::SolverState AdvanceState()
//------------------------------------------------------------------------------
/**
* The method used to iterate until a solution is found. Derived classes
* use this method to implement their solution technique.
*
* @return solver state at the end of the process.
*/
//------------------------------------------------------------------------------
Solver::SolverState Solver::AdvanceState()
{
switch (currentState) {
case INITIALIZING:
CompleteInitialization();
break;
case NOMINAL:
RunNominal();
status = RUN;
break;
case PERTURBING:
RunPerturbation();
break;
case ITERATING:
RunIteration();
break;
case CALCULATING:
CalculateParameters();
break;
case CHECKINGRUN:
CheckCompletion();
break;
case RUNEXTERNAL:
RunExternal();
break;
case FINISHED:
RunComplete();
break;
default:
throw SolverException("Undefined Solver state");
};
ReportProgress();
return currentState;
}
//------------------------------------------------------------------------------
// StringArray AdvanceNestedState(std::vector<Real> vars)
//------------------------------------------------------------------------------
/**
* The method used to iterate until a solution is found. Derived classes
* must implement this method (this default method throws an exception).
*
* @return TBD
*/
//------------------------------------------------------------------------------
StringArray Solver::AdvanceNestedState(std::vector<Real> vars)
{
std::string errorStr = "AdvanceNestedState not implemented for solver "
+ instanceName;
throw SolverException(errorStr);
}
//------------------------------------------------------------------------------
// bool UpdateSolverGoal(Integer id, Real newValue)
//------------------------------------------------------------------------------
/**
* Updates the targeter goals, for floating end point problems.
*
* This default method just returns false.
*
* @param id Id for the goal that is being reset.
* @param newValue The new goal value.
*
* @return The ID used for this variable.
*/
//------------------------------------------------------------------------------
bool Solver::UpdateSolverGoal(Integer id, Real newValue)
{
return false;
}
//------------------------------------------------------------------------------
// bool UpdateSolverTolerance(Integer id, Real newValue)
//------------------------------------------------------------------------------
/**
* Updates the targeter tolerances, for floating end point problems.
*
* This default method just returns false.
*
* @param id Id for the tolerance that is being reset.
* @param newValue The new tolerance value.
*
* @return The ID used for this variable.
*/
//------------------------------------------------------------------------------
bool Solver::UpdateSolverTolerance(Integer id, Real newValue)
{
return false;
}
// Access methods overriden from the base class
//------------------------------------------------------------------------------
// std::string GetParameterText(const Integer id) const
//------------------------------------------------------------------------------
/**
* This method returns the parameter text, given the input parameter ID.
*
* @param <id> Id for the requested parameter text.
*
* @return parameter text for the requested parameter.
*/
//------------------------------------------------------------------------------
std::string Solver::GetParameterText(const Integer id) const
{
if ((id >= GmatBaseParamCount) && (id < SolverParamCount))
{
//MessageInterface::ShowMessage("'%s':\n",
// PARAMETER_TEXT[id - GmatBaseParamCount].c_str());
return PARAMETER_TEXT[id - GmatBaseParamCount];
}
return GmatBase::GetParameterText(id);
}
//------------------------------------------------------------------------------
// Integer GetParameterID(const std::string &str) const
//------------------------------------------------------------------------------
/**
* This method returns the parameter ID, given the input parameter string.
*
* @param <str> string for the requested parameter.
*
* @return ID for the requested parameter.
*/
//------------------------------------------------------------------------------
Integer Solver::GetParameterID(const std::string &str) const
{
// Write deprecated message per GMAT session
static bool writeDeprecatedMsg = true;
// 1. This part will be removed for a future build:
std::string param_text = str;
if (param_text == "TargeterTextFile")
{
if (writeDeprecatedMsg)
{
MessageInterface::ShowMessage
(deprecatedMessageFormat.c_str(), "TargeterTextFile", GetName().c_str(),
"ReportFile");
writeDeprecatedMsg = false;
}
param_text = "ReportFile";
}
// 2. This part is kept for a future build:
for (Integer i = GmatBaseParamCount; i < SolverParamCount; ++i)
{
if (param_text == PARAMETER_TEXT[i - GmatBaseParamCount])
return i;
}
return GmatBase::GetParameterID(str);
}
//------------------------------------------------------------------------------
// Gmat::ParameterType GetParameterType(const Integer id) const
//------------------------------------------------------------------------------
/**
* This method returns the parameter type, given the input parameter ID.
*
* @param <id> ID for the requested parameter.
*
* @return parameter type of the requested parameter.
*/
//------------------------------------------------------------------------------
Gmat::ParameterType Solver::GetParameterType(const Integer id) const
{
if ((id >= GmatBaseParamCount) && (id < SolverParamCount))
return PARAMETER_TYPE[id - GmatBaseParamCount];
return GmatBase::GetParameterType(id);
}
//------------------------------------------------------------------------------
// std::string GetParameterTypeString(const Integer id) const
//------------------------------------------------------------------------------
/**
* This method returns the parameter type string, given the input parameter ID.
*
* @param <id> ID for the requested parameter.
*
* @return parameter type string of the requested parameter.
*/
//------------------------------------------------------------------------------
std::string Solver::GetParameterTypeString(const Integer id) const
{
return GmatBase::PARAM_TYPE_STRING[GetParameterType(id)];
}
//---------------------------------------------------------------------------
// bool IsParameterReadOnly(const Integer id) const
//---------------------------------------------------------------------------
/**
* Checks to see if the requested parameter is read only.
*
* @param <id> Description for the parameter.
*
* @return true if the parameter is read only, false (the default) if not,
* throws if the parameter is out of the valid range of values.
*/
//---------------------------------------------------------------------------
bool Solver::IsParameterReadOnly(const Integer id) const
{
if ((id == NUMBER_OF_VARIABLES) ||
(id == variableNamesID) ||
(id == RegisteredVariables) ||
(id == RegisteredComponents) ||
(id == AllowRangeSettings) ||
(id == AllowStepsizeSetting) ||
(id == AllowScaleSetting) ||
(id == AllowVariablePertSetting) ||
(id == SolverModeID) ||
(id == ExitModeID) ||
(id == SolverStatusID))
return true;
return GmatBase::IsParameterReadOnly(id);
}
//---------------------------------------------------------------------------
// bool IsParameterReadOnly(const std::string &label) const
//---------------------------------------------------------------------------
/**
* Checks to see if the requested parameter is read only.
*
* @param <label> Description for the parameter.
*
* @return true if the parameter is read only, false (the default) if not.
*/
//---------------------------------------------------------------------------
bool Solver::IsParameterReadOnly(const std::string &label) const
{
return IsParameterReadOnly(GetParameterID(label));
}
//------------------------------------------------------------------------------
// Integer GetIntegerParameter(const Integer id) const
//------------------------------------------------------------------------------
/**
* This method returns an Integer parameter value, given the input
* parameter ID.
*
* @param <id> ID for the requested parameter.
*
* @return Integer value of the requested parameter.
*/
//------------------------------------------------------------------------------
Integer Solver::GetIntegerParameter(const Integer id) const
{
if (id == maxIterationsID)
return maxIterations;
if (id == NUMBER_OF_VARIABLES)
return variableCount;
if (id == SolverStatusID)
return status;
return GmatBase::GetIntegerParameter(id);
}
//------------------------------------------------------------------------------
// Integer SetIntegerParameter(const Integer id, const Integer value)
//------------------------------------------------------------------------------
/**
* This method sets an Integer parameter value, given the input
* parameter ID.
*
* @param <id> ID for the requested parameter.
* @param <value> Integer value for the parameter.
*
* @return The value of the parameter at the completion of the call.
*/
//------------------------------------------------------------------------------
Integer Solver::SetIntegerParameter(const Integer id,
const Integer value)
{
if (id == maxIterationsID)
{
if (value > 0)
maxIterations = value;
else
throw SolverException(
"The value entered for the maximum iterations on " + instanceName +
" is not an allowed value. The allowed value is: [Integer > 0].");
return maxIterations;
}
if (id == RegisteredVariables)
{
registeredVariableCount = value;
return registeredVariableCount;
}
if (id == RegisteredComponents)
{
registeredComponentCount = value;
return registeredComponentCount;
}
return GmatBase::SetIntegerParameter(id, value);
}
//------------------------------------------------------------------------------
// bool GetBooleanParameter(const Integer id) const
//------------------------------------------------------------------------------
/**
* This method returns the Boolean parameter value, given the input
* parameter ID.
*
* @param <id> ID for the requested parameter.
*
* @return Boolean value of the requested parameter.
*
*/
//------------------------------------------------------------------------------
bool Solver::GetBooleanParameter(const Integer id) const
{
if (id == ShowProgressID)
return showProgress;
if (id == AllowScaleSetting)
return AllowScaleFactors;
if (id == AllowRangeSettings)
return AllowRangeLimits;
if (id == AllowStepsizeSetting)
return AllowStepsizeLimit;
if (id == AllowVariablePertSetting)
return AllowIndependentPerts;
return GmatBase::GetBooleanParameter(id);
}
//------------------------------------------------------------------------------
// Integer SetBooleanParameter(const Integer id, const bool value)
//------------------------------------------------------------------------------
/**
* This method sets a Boolean parameter value, given the input
* parameter ID.
*
* @param <id> ID for the requested parameter.
* @param <value> Boolean value for the parameter.
*
* @return The value of the parameter at the completion of the call.
*/
//------------------------------------------------------------------------------
bool Solver::SetBooleanParameter(const Integer id, const bool value)
{
if (id == ShowProgressID)
{
showProgress = value;
return showProgress;
}
return GmatBase::SetBooleanParameter(id, value);
}
//---------------------------------------------------------------------------
// std::string GetStringParameter(const Integer id) const
//---------------------------------------------------------------------------
/**
* Retrieve a string parameter.
*
* @param <id> The integer ID for the parameter.
*
* @return The string stored for this parameter, or throw ab=n exception if
* there is no string association.
*/
//---------------------------------------------------------------------------
std::string Solver::GetStringParameter(const Integer id) const
{
if (id == ReportStyle)
return textFileMode;
if (id == solverTextFileID)
return solverTextFile;
return GmatBase::GetStringParameter(id);
}
//---------------------------------------------------------------------------
// std::string GetStringParameter(const std::string &label) const
//---------------------------------------------------------------------------
/**
* Retrieve a string parameter.
*
* @param <id> The integer ID for the parameter.
*
* @return The string stored for this parameter, or throw ab=n exception if
* there is no string association.
*/
//---------------------------------------------------------------------------
std::string Solver::GetStringParameter(const std::string &label) const
{
return GetStringParameter(GetParameterID(label));
}
//---------------------------------------------------------------------------
// bool SetStringParameter(const Integer id, const std::string &value)
//---------------------------------------------------------------------------
/**
* Change the value of a string parameter.
*
* @param <id> The integer ID for the parameter.
* @param <value> The new string for this parameter.
*
* @return true if the string is stored, throw if the parameter is not stored.
*/
//---------------------------------------------------------------------------
bool Solver::SetStringParameter(const Integer id, const std::string &value)
{
#ifdef DEBUG_PARAM_SET
MessageInterface::ShowMessage
("Solver::SetStringParameter() <%p><%s>'%s' entered, id=%d, value='%s'\n",
this, GetTypeName().c_str(), GetName().c_str(), id, value.c_str());
#endif
if (id == ReportStyle)
{
for (Integer i = NORMAL_STYLE; i < MaxStyle; ++i)
{
if (value == STYLE_TEXT[i-NORMAL_STYLE])
{
textFileMode = value;
progressStyle = i;
return true;
}
}
throw SolverException(
"The value of \"" + value + "\" for field \"Report Style\""
" on object \"" + instanceName + "\" is not an allowed value.\n"
"The allowed values are: [Normal, Concise, Verbose, Debug].");
}
if (id == solverTextFileID)
{
solverTextFile = value;
return true;
}
if (id == variableNamesID)
{
variableNames.push_back(value);
return true;
}
if (id == SolverModeID)
{
if (value == "Solve")
currentMode = SOLVE;
else if (value == "RunInitialGuess")
currentMode = INITIAL_GUESS;
else if (value == "RunCorrected")
currentMode = RUN_CORRECTED;
else
throw SolverException("Solver mode " + value +
"not recognized; allowed values are {\"Solve\", "
"\"RunInitialGuess\", \"RunCorrected\"}");
solverMode = value;
return true;
}
if (id == ExitModeID)
{
#ifdef DEBUG_SOLVEANDCONTINUE
MessageInterface::ShowMessage("%s setting ExitMode to %s (old id %d",
instanceName.c_str(), value.c_str(), exitMode);
#endif
if (value == "DiscardAndContinue")
exitMode = DISCARD;
else if (value == "SaveAndContinue")
exitMode = RETAIN;
else if (value == "Stop")
exitMode = HALT;
else
throw SolverException("Exit mode " + value +
"not recognized; allowed values are {\"DiscardAndContinue\", "
"\"SaveAndContinue\", \"Stop\"}");
exitModeText = value;
#ifdef DEBUG_SOLVEANDCONTINUE
MessageInterface::ShowMessage(", new id %d)\n", exitMode);
#endif
return true;
}
return GmatBase::SetStringParameter(id, value);
}
//---------------------------------------------------------------------------
// bool SetStringParameter(const Integer id, const std::string &value)
//---------------------------------------------------------------------------
/**
* Change the value of a string parameter.
*
* @param <id> The integer ID for the parameter.
* @param <value> The new string for this parameter.
*
* @return true if the string is stored, throw if the parameter is not stored.
*/
bool Solver::SetStringParameter(const std::string &label,
const std::string &value)
{
return SetStringParameter(GetParameterID(label), value);
}
std::string Solver::GetStringParameter(const Integer id,
const Integer index) const
{
return GmatBase::GetStringParameter(id, index);
}
bool Solver::SetStringParameter(const Integer id,
const std::string &value,
const Integer index)
{
return GmatBase::SetStringParameter(id, value, index);
}
std::string Solver::GetStringParameter(const std::string &label,
const Integer index) const
{
return GmatBase::GetStringParameter(label, index);
}
bool Solver::SetStringParameter(const std::string &label,
const std::string &value,
const Integer index)
{
return GmatBase::SetStringParameter(label, value, index);
}
//------------------------------------------------------------------------------
// std::string GetStringArrayParameter(const Integer id) const
//------------------------------------------------------------------------------
/**
* This method returns the string parameter value, given the input
* parameter ID.
*
* @param <id> ID for the requested parameter.
*
* @return StringArray value of the requested parameter.
*/
//------------------------------------------------------------------------------
const StringArray& Solver::GetStringArrayParameter(const Integer id) const
{
if (id == variableNamesID)
return variableNames;
return GmatBase::GetStringArrayParameter(id);
}
//------------------------------------------------------------------------------
// const StringArray& GetPropertyEnumStrings(const Integer id) const
//------------------------------------------------------------------------------
/**
* Returns the list of allowable settings for the enumerated parameters
*
* @param id The ID of the parameter
*
* @return A const string array with the allowed settings.
*/
//------------------------------------------------------------------------------
const StringArray& Solver::GetPropertyEnumStrings(const Integer id) const
{
static StringArray enumStrings;
enumStrings.clear();
if (id == ReportStyle)
{
enumStrings.push_back("Normal");
enumStrings.push_back("Concise");
enumStrings.push_back("Verbose");
enumStrings.push_back("Debug");
return enumStrings;
}
return GmatBase::GetPropertyEnumStrings(id);
}
//------------------------------------------------------------------------------
// void ReportProgress()
//------------------------------------------------------------------------------
/**
* Shows the progress string to the user.
*
* This default version just passes the progress string to the MessageInterface.
*/
//------------------------------------------------------------------------------
void Solver::ReportProgress(const SolverState forState)
{
SolverState stateBuffer = currentState;
if (forState != UNDEFINED_STATE)
currentState = forState;
if (showProgress)
{
MessageInterface::ShowMessage("%s\n", GetProgressString().c_str());
}
currentState = stateBuffer;
}
//------------------------------------------------------------------------------
// void SetDebugString(const std::string &str)
//------------------------------------------------------------------------------
/**
* Fills the buffer with run data for (user space) debug mode in the Solvers.
*
* @param <str> The data passed from the command stream.
*/
//------------------------------------------------------------------------------
void Solver::SetDebugString(const std::string &str)
{
debugString = str;
}
//------------------------------------------------------------------------------
// void CompleteInitialization()
//------------------------------------------------------------------------------
/**
* Finalized the initialization process by setting the current state for the
* state machine to the entry state for the solver. The default method provided
* here sets the state to the NOMINAL state.
*/
//------------------------------------------------------------------------------
void Solver::CompleteInitialization()
{
OpenSolverTextFile();
WriteToTextFile();
currentState = NOMINAL;
// Reset initial values if in DiscardAndContinue mode
if (exitMode == DISCARD)
{
#ifdef DEBUG_SAVEANDCONTINUE
MessageInterface::ShowMessage("%s is resetting variables\n",
instanceName.c_str());
#endif
ResetVariables();
}
}
//------------------------------------------------------------------------------
// void RunNominal()
//------------------------------------------------------------------------------
/**
* Executes a nominal run and then advances the state machine to the next state.
*
* This default method just advances the state.
*/
//------------------------------------------------------------------------------
void Solver::RunNominal()
{
currentState = (SolverState)(currentState+1);
}
//------------------------------------------------------------------------------
// void RunPerturbation()
//------------------------------------------------------------------------------
/**
* Executes a perturbation run and then advances the state machine to the next
* state.
*
* This default method just advances the state.
*/
//------------------------------------------------------------------------------
void Solver::RunPerturbation()
{
currentState = (SolverState)(currentState+1);
}
//------------------------------------------------------------------------------
// void RunIteration()
//------------------------------------------------------------------------------
/**
* Executes an iteration run and then advances the state machine to the next
* state.
*
* This default method just advances the state.
*/
//------------------------------------------------------------------------------
void Solver::RunIteration()
{
currentState = (SolverState)(currentState+1);
}
//------------------------------------------------------------------------------
// void CalculateParameters()
//------------------------------------------------------------------------------
/**
* Executes a Calculates parameters needed by the state machine for the next
* nominal run, and then advances the state machine to the next state.
*
* This default method just advances the state.
*/
//------------------------------------------------------------------------------
void Solver::CalculateParameters()
{
currentState = (SolverState)(currentState+1);
}
//------------------------------------------------------------------------------
// void CheckCompletion()
//------------------------------------------------------------------------------
/**
* Checks to see if the Solver has converged.
*
* This default method just advances the state.
*/
//------------------------------------------------------------------------------
void Solver::CheckCompletion()
{
currentState = (SolverState)(currentState+1);
}
//------------------------------------------------------------------------------
// void RunExternal()
//------------------------------------------------------------------------------
/**
* Launhes an external process that drives the Solver.
*
* This default method just ???? (not a clue).
*/
//------------------------------------------------------------------------------
void Solver::RunExternal()
{
//currentState = FINISHED; // what to do here?
currentState = (SolverState)(currentState+1);
hasFired = true;
}
//------------------------------------------------------------------------------
// void RunComplete()
//------------------------------------------------------------------------------
/**
* Finalized the data at the end of a run.
*
* This default method just sets the state to FINISHED.
*/
//------------------------------------------------------------------------------
void Solver::RunComplete()
{
currentState = FINISHED;
}
//------------------------------------------------------------------------------
// void ResetVariables()
//------------------------------------------------------------------------------
/**
* Reset the variable data to its initial values.
*/
//------------------------------------------------------------------------------
void Solver::ResetVariables()
{
variable = variableInitialValues;
}
//------------------------------------------------------------------------------
// std::string GetProgressString()
//------------------------------------------------------------------------------
/**
* Generates a string that is written out by solvers when showProgress is true.
*/
//------------------------------------------------------------------------------
std::string Solver::GetProgressString()
{
return "Solver progress string not yet implemented for " + typeName;
}
//------------------------------------------------------------------------------
// void FreeArrays()
//------------------------------------------------------------------------------
/**
* Frees the memory used by the targeter, so it can be reused later in the
* sequence. This method is also called by the destructor when the script is
* cleared.
*/
//------------------------------------------------------------------------------
void Solver::FreeArrays()
{
variable.clear();
variableInitialValues.clear();
perturbation.clear();
variableMinimum.clear();
variableMaximum.clear();
variableMaximumStep.clear();
pertDirection.clear();
}
//------------------------------------------------------------------------------
// void OpenSolverTextFile();
//------------------------------------------------------------------------------
void Solver::OpenSolverTextFile()
{
#ifdef DEBUG_SOLVER_INIT
MessageInterface::ShowMessage
("Solver::OpenSolverTextFile() <%p><%s>'%s' entered\n showProgress=%d, "
"solverTextFile='%s', textFileOpen=%d\n", this, GetTypeName().c_str(),
GetName().c_str(), showProgress, solverTextFile.c_str(), textFile.is_open());
#endif
if (!showProgress)
return;
FileManager *fm;
fm = FileManager::Instance();
std::string outPath = fm->GetFullPathname(FileManager::OUTPUT_PATH);
std::string fullSolverTextFile = solverTextFile;
// Add output path if there is no path (LOJ: 2012.04.19 for GMT-1542 fix)
if (solverTextFile.find("/") == solverTextFile.npos &&
solverTextFile.find("\\") == solverTextFile.npos)
fullSolverTextFile = outPath + solverTextFile;
if (textFile.is_open())
textFile.close();
#ifdef DEBUG_SOLVER_INIT
MessageInterface::ShowMessage(" fullSolverTextFile='%s'\n", fullSolverTextFile.c_str());
MessageInterface::ShowMessage(" instanceNumber=%d\n", instanceNumber);
#endif
if (instanceNumber == 1)
textFile.open(fullSolverTextFile.c_str());
else
textFile.open(fullSolverTextFile.c_str(), std::ios::app);
if (!textFile.is_open())
throw SolverException("Error opening targeter text file " +
fullSolverTextFile);
textFile.precision(16);
#ifdef DEBUG_SOLVER_INIT
MessageInterface::ShowMessage("Solver::OpenSolverTextFile() leaving\n");
#endif
}
|
// -*- c-basic-offset: 4 -*-
#ifndef CLICK_BURSTSTATS_HH
#define CLICK_BURSTSTATS_HH
#include <click/batchelement.hh>
#include <click/multithread.hh>
#include <click/vector.hh>
#include <click/statvector.hh>
CLICK_DECLS
/*
=c
BurstStats
=s counters
keep statistics about bursts, defined as the number of packets from the same flow following each others
=d
handlers
* average : Average burst size
* median : Median burst size
* dump : Print the number of batches for each size seen
*/
class BurstStats : public SimpleElement<BurstStats>, public StatVector<int> { public:
BurstStats() CLICK_COLD;
~BurstStats() CLICK_COLD;
const char *class_name() const override { return "BurstStats"; }
const char *port_count() const override { return PORTS_1_1; }
void * cast(const char *name);
int configure(Vector<String> &, ErrorHandler *) CLICK_COLD;
int initialize(ErrorHandler *) CLICK_COLD;
void cleanup(CleanupStage) CLICK_COLD;
Packet *simple_action(Packet *) override;
void add_handlers();
struct BurstStatsState {
BurstStatsState() : burstlen(0) {
}
int burstlen;
int last_anno;
};
per_thread<BurstStatsState> s;
};
CLICK_ENDDECLS
#endif
|
.eqv SYS_PRINT_WORD 1
.eqv SYS_PRINT_STRING 4
.eqv SYS_READ_WORD 5
.eqv SYS_READ_STRING 8
.eqv SYS_EXIT 10
.eqv SYS_PRINT_CHAR 11
.eqv SYS_READ_CHAR 12
.macro endl()
li $v0, SYS_PRINT_CHAR
li $a0, 0xa
syscall
.end_macro
.data
str1: .asciiz "Hello\n"
str2: .asciiz "TEI\n"
name: .space 64
.text
.globl _main
_main:
# 1. print a character
li $v0, SYS_PRINT_CHAR
li $a0, 'C'
syscall
endl()
# 2. print characters 'a' and 'd'
li $a0, 'a'
syscall
li $a0, 'd'
syscall
endl()
# 3. print 'Hello'
li $v0, SYS_PRINT_STRING
la $a0, str1
syscall
# 4. print 'Hello' and 'TEI'
la $a0, str1
syscall
la $a0, str2
syscall
# 5. print 5
li $v0, SYS_PRINT_WORD
li $a0, 5
syscall
endl()
# 6. read a word and print it
li $v0, SYS_READ_WORD
syscall
move $t0, $v0
li $v0, SYS_PRINT_WORD
la $a0, 0($t0)
syscall
endl()
# 7. read name, store in mem and print it
li $v0, SYS_READ_STRING
la $a0, name
li $a1, 64
syscall
li $v0, SYS_PRINT_STRING
syscall
li $v0, SYS_EXIT
syscall
|
.init main
.float lhs 1.0
.float rhs 2.0
.code
load_values:
mov i1 @0 ; Load constants from 0 slot
mov i5 &lhs ; At offset of data item
lqw i1 i5 i0 ; Load LHS into i0 (retrieve data)
mov i5 &rhs ; At offset of data item
lqw i1 i5 i1 ; Load RHS into i1 (retrieve data)
ret
killing_floor:
aseq x0 x1 ; Can never be true (constant 0, constant 1)
ret
main:
call load_values
bltf i1 i0 killing_floor ; None of these should hit
bgtf i0 i1 killing_floor
beqf i0 i1 killing_floor
bltf i0 i1 spot_one
jmp killing_floor ; Should jump over
spot_one:
bgtf i1 i0 spot_two
jmp killing_floor ; Should jump over
spot_two:
beqf i0 i0 spot_three
jmp killing_floor ; Should jump over
spot_three:
mov i0 @0
exit
|
; ===============================================================
; Dec 2013
; ===============================================================
;
; char *strncat(char * restrict s1, const char * restrict s2, size_t n)
;
; Append at most n chars from string s2 to the end of string s1,
; return s1. s1 is always terminated with a 0.
;
; The maximum length of s1 will be strlen(s1) + n + 1
;
; ===============================================================
SECTION code_clib
SECTION code_string
PUBLIC asm_strncat
PUBLIC asm0_strncat
EXTERN __str_locate_nul
asm_strncat:
; enter : hl = char *s2 = src
; de = char *s1 = dst
; bc = size_t n
;
; exit : hl = char *s1 = dst
; de = ptr in s1 to terminating 0
; carry set if all of s2 not appended
;
; uses : af, bc, de, hl
ld a,b
or c
jr Z,zero_n
asm0_strncat:
push de ; save dst
push bc
ex de,hl
call __str_locate_nul ; a = 0
ex de,hl
pop bc
loop: ; append src to dst
IF __CPU_INTEL__ || __CPU_GBZ80__
ld a,(hl)
and a
jr Z,done
ld (de),a
inc hl
inc de
dec bc
ld a,b
or c
jr NZ,loop
ELSE
cp (hl)
jr Z,done
ldi
jp PE,loop
ENDIF
scf
done:
ld (de),a ; terminate dst
pop hl
ret
zero_n:
ld hl,de
scf
ret
|
; void adt_StackDelete(struct adt_Stack *s, void *delete)
; CALLER linkage for function pointers
PUBLIC adt_StackDelete
EXTERN adt_StackDelete_callee
EXTERN ASMDISP_ADT_STACKDELETE_CALLEE
.adt_StackDelete
pop bc
pop de
pop hl
push hl
push de
push bc
jp adt_StackDelete_callee + ASMDISP_ADT_STACKDELETE_CALLEE
|
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINER_FLAT_SET_HPP
#define BOOST_CONTAINER_FLAT_SET_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>
// container
#include <boost/container/allocator_traits.hpp>
#include <boost/container/container_fwd.hpp>
#include <boost/container/new_allocator.hpp> //new_allocator
// container/detail
#include <boost/container/detail/flat_tree.hpp>
#include <boost/container/detail/mpl.hpp>
// move
#include <boost/move/traits.hpp>
#include <boost/move/utility_core.hpp>
// move/detail
#if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#include <boost/move/detail/fwd_macros.hpp>
#endif
#include <boost/move/detail/move_helpers.hpp>
// intrusive/detail
#include <boost/intrusive/detail/minimal_pair_header.hpp> //pair
#include <boost/intrusive/detail/minimal_less_equal_header.hpp>//less, equal
// std
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
#include <initializer_list>
#endif
namespace boost {
namespace container {
#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
template <class Key, class Compare, class AllocatorOrContainer>
class flat_multiset;
#endif
//! flat_set is a Sorted Associative Container that stores objects of type Key.
//! It is also a Unique Associative Container, meaning that no two elements are the same.
//!
//! flat_set is similar to std::set but it's implemented by as an ordered sequence container.
//! The underlying sequence container is by default <i>vector</i> but it can also work
//! user-provided vector-like SequenceContainers (like <i>static_vector</i> or <i>small_vector</i>).
//!
//! Using vector-like sequence containers means that inserting a new element into a flat_set might invalidate
//! previous iterators and references (unless that sequence container is <i>stable_vector</i> or a similar
//! container that offers stable pointers and references). Similarly, erasing an element might invalidate
//! iterators and references pointing to elements that come after (their keys are bigger) the erased element.
//!
//! This container provides random-access iterators.
//!
//! \tparam Key is the type to be inserted in the set, which is also the key_type
//! \tparam Compare is the comparison functor used to order keys
//! \tparam AllocatorOrContainer is either:
//! - The allocator to allocate <code>value_type</code>s (e.g. <i>allocator< std::pair<Key, T> > </i>).
//! (in this case <i>sequence_type</i> will be vector<value_type, AllocatorOrContainer>)
//! - The SequenceContainer to be used as the underlying <i>sequence_type</i>. It must be a vector-like
//! sequence container with random-access iterators.
#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
template <class Key, class Compare = std::less<Key>, class AllocatorOrContainer = new_allocator<Key> >
#else
template <class Key, class Compare, class AllocatorOrContainer>
#endif
class flat_set
///@cond
: public dtl::flat_tree<Key, dtl::identity<Key>, Compare, AllocatorOrContainer>
///@endcond
{
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
private:
BOOST_COPYABLE_AND_MOVABLE(flat_set)
typedef dtl::flat_tree<Key, dtl::identity<Key>, Compare, AllocatorOrContainer> tree_t;
public:
tree_t &tree()
{ return *this; }
const tree_t &tree() const
{ return *this; }
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
public:
//////////////////////////////////////////////
//
// types
//
//////////////////////////////////////////////
typedef Key key_type;
typedef Compare key_compare;
typedef Key value_type;
typedef typename BOOST_CONTAINER_IMPDEF(tree_t::sequence_type) sequence_type;
typedef typename sequence_type::allocator_type allocator_type;
typedef ::boost::container::allocator_traits<allocator_type> allocator_traits_type;
typedef typename sequence_type::pointer pointer;
typedef typename sequence_type::const_pointer const_pointer;
typedef typename sequence_type::reference reference;
typedef typename sequence_type::const_reference const_reference;
typedef typename sequence_type::size_type size_type;
typedef typename sequence_type::difference_type difference_type;
typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type;
typedef typename BOOST_CONTAINER_IMPDEF(tree_t::value_compare) value_compare;
typedef typename sequence_type::iterator iterator;
typedef typename sequence_type::const_iterator const_iterator;
typedef typename sequence_type::reverse_iterator reverse_iterator;
typedef typename sequence_type::const_reverse_iterator const_reverse_iterator;
public:
//////////////////////////////////////////////
//
// construct/copy/destroy
//
//////////////////////////////////////////////
//! <b>Effects</b>: Default constructs an empty container.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE
flat_set() BOOST_NOEXCEPT_IF(dtl::is_nothrow_default_constructible<AllocatorOrContainer>::value &&
dtl::is_nothrow_default_constructible<Compare>::value)
: tree_t()
{}
//! <b>Effects</b>: Constructs an empty container using the specified
//! comparison object.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE
explicit flat_set(const Compare& comp)
: tree_t(comp)
{}
//! <b>Effects</b>: Constructs an empty container using the specified allocator.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE
explicit flat_set(const allocator_type& a)
: tree_t(a)
{}
//! <b>Effects</b>: Constructs an empty container using the specified
//! comparison object and allocator.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE
flat_set(const Compare& comp, const allocator_type& a)
: tree_t(comp, a)
{}
//! <b>Effects</b>: Constructs an empty container and
//! inserts elements from the range [first ,last ).
//!
//! <b>Complexity</b>: Linear in N if the range [first ,last ) is already sorted using
//! comp and otherwise N logN, where N is last - first.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE
flat_set(InputIterator first, InputIterator last)
: tree_t(true, first, last)
{}
//! <b>Effects</b>: Constructs an empty container using the specified
//! allocator, and inserts elements from the range [first ,last ).
//!
//! <b>Complexity</b>: Linear in N if the range [first ,last ) is already sorted using
//! comp and otherwise N logN, where N is last - first.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE
flat_set(InputIterator first, InputIterator last, const allocator_type& a)
: tree_t(true, first, last, a)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! inserts elements from the range [first ,last ).
//!
//! <b>Complexity</b>: Linear in N if the range [first ,last ) is already sorted using
//! comp and otherwise N logN, where N is last - first.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE
flat_set(InputIterator first, InputIterator last, const Compare& comp)
: tree_t(true, first, last, comp)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! allocator, and inserts elements from the range [first ,last ).
//!
//! <b>Complexity</b>: Linear in N if the range [first ,last ) is already sorted using
//! comp and otherwise N logN, where N is last - first.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE
flat_set(InputIterator first, InputIterator last, const Compare& comp, const allocator_type& a)
: tree_t(true, first, last, comp, a)
{}
//! <b>Effects</b>: Constructs an empty container and
//! inserts elements from the ordered unique range [first ,last). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE
flat_set(ordered_unique_range_t, InputIterator first, InputIterator last)
: tree_t(ordered_unique_range, first, last)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! inserts elements from the ordered unique range [first ,last). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE
flat_set(ordered_unique_range_t, InputIterator first, InputIterator last, const Compare& comp)
: tree_t(ordered_unique_range, first, last, comp)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! allocator, and inserts elements from the ordered unique range [first ,last). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE
flat_set(ordered_unique_range_t, InputIterator first, InputIterator last, const Compare& comp, const allocator_type& a)
: tree_t(ordered_unique_range, first, last, comp, a)
{}
//! <b>Effects</b>: Constructs an empty container using the specified allocator and
//! inserts elements from the ordered unique range [first ,last). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE
flat_set(ordered_unique_range_t, InputIterator first, InputIterator last, const allocator_type& a)
: tree_t(ordered_unique_range, first, last, Compare(), a)
{}
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! <b>Effects</b>: Constructs an empty container and
//! inserts elements from the range [il.begin(), il.end()).
//!
//! <b>Complexity</b>: Linear in N if the range [il.begin(), il.end()) is already sorted using
//! comp and otherwise N logN, where N is il.begin() - il.end().
BOOST_CONTAINER_FORCEINLINE flat_set(std::initializer_list<value_type> il)
: tree_t(true, il.begin(), il.end())
{}
//! <b>Effects</b>: Constructs an empty container using the specified
//! allocator, and inserts elements from the range [il.begin(), il.end()).
//!
//! <b>Complexity</b>: Linear in N if the range [il.begin(), il.end()) is already sorted using
//! comp and otherwise N logN, where N is il.begin() - il.end().
BOOST_CONTAINER_FORCEINLINE flat_set(std::initializer_list<value_type> il, const allocator_type& a)
: tree_t(true, il.begin(), il.end(), a)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! inserts elements from the range [il.begin(), il.end()).
//!
//! <b>Complexity</b>: Linear in N if the range [il.begin(), il.end()) is already sorted using
//! comp and otherwise N logN, where N is il.begin() - il.end().
BOOST_CONTAINER_FORCEINLINE flat_set(std::initializer_list<value_type> il, const Compare& comp)
: tree_t(true, il.begin(), il.end(), comp)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! allocator, and inserts elements from the range [il.begin(), il.end()).
//!
//! <b>Complexity</b>: Linear in N if the range [il.begin(), il.end()) is already sorted using
//! comp and otherwise N logN, where N is il.begin() - il.end().
BOOST_CONTAINER_FORCEINLINE flat_set(std::initializer_list<value_type> il, const Compare& comp, const allocator_type& a)
: tree_t(true, il.begin(), il.end(), comp, a)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! inserts elements from the ordered unique range [il.begin(), il.end()). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [il.begin(), il.end()) must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
BOOST_CONTAINER_FORCEINLINE flat_set(ordered_unique_range_t, std::initializer_list<value_type> il)
: tree_t(ordered_unique_range, il.begin(), il.end())
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! inserts elements from the ordered unique range [il.begin(), il.end()). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [il.begin(), il.end()) must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
BOOST_CONTAINER_FORCEINLINE flat_set(ordered_unique_range_t, std::initializer_list<value_type> il, const Compare& comp)
: tree_t(ordered_unique_range, il.begin(), il.end(), comp)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! allocator, and inserts elements from the ordered unique range [il.begin(), il.end()). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [il.begin(), il.end()) must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
BOOST_CONTAINER_FORCEINLINE flat_set(ordered_unique_range_t, std::initializer_list<value_type> il, const Compare& comp, const allocator_type& a)
: tree_t(ordered_unique_range, il.begin(), il.end(), comp, a)
{}
#endif
//! <b>Effects</b>: Copy constructs the container.
//!
//! <b>Complexity</b>: Linear in x.size().
BOOST_CONTAINER_FORCEINLINE flat_set(const flat_set& x)
: tree_t(static_cast<const tree_t&>(x))
{}
//! <b>Effects</b>: Move constructs thecontainer. Constructs *this using x's resources.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Postcondition</b>: x is emptied.
BOOST_CONTAINER_FORCEINLINE flat_set(BOOST_RV_REF(flat_set) x)
BOOST_NOEXCEPT_IF(boost::container::dtl::is_nothrow_move_constructible<Compare>::value)
: tree_t(BOOST_MOVE_BASE(tree_t, x))
{}
//! <b>Effects</b>: Copy constructs a container using the specified allocator.
//!
//! <b>Complexity</b>: Linear in x.size().
BOOST_CONTAINER_FORCEINLINE flat_set(const flat_set& x, const allocator_type &a)
: tree_t(static_cast<const tree_t&>(x), a)
{}
//! <b>Effects</b>: Move constructs a container using the specified allocator.
//! Constructs *this using x's resources.
//!
//! <b>Complexity</b>: Constant if a == x.get_allocator(), linear otherwise
BOOST_CONTAINER_FORCEINLINE flat_set(BOOST_RV_REF(flat_set) x, const allocator_type &a)
: tree_t(BOOST_MOVE_BASE(tree_t, x), a)
{}
//! <b>Effects</b>: Makes *this a copy of x.
//!
//! <b>Complexity</b>: Linear in x.size().
BOOST_CONTAINER_FORCEINLINE flat_set& operator=(BOOST_COPY_ASSIGN_REF(flat_set) x)
{ return static_cast<flat_set&>(this->tree_t::operator=(static_cast<const tree_t&>(x))); }
//! <b>Throws</b>: If allocator_traits_type::propagate_on_container_move_assignment
//! is false and (allocation throws or value_type's move constructor throws)
//!
//! <b>Complexity</b>: Constant if allocator_traits_type::
//! propagate_on_container_move_assignment is true or
//! this->get>allocator() == x.get_allocator(). Linear otherwise.
BOOST_CONTAINER_FORCEINLINE flat_set& operator=(BOOST_RV_REF(flat_set) x)
BOOST_NOEXCEPT_IF( (allocator_traits_type::propagate_on_container_move_assignment::value ||
allocator_traits_type::is_always_equal::value) &&
boost::container::dtl::is_nothrow_move_assignable<Compare>::value)
{ return static_cast<flat_set&>(this->tree_t::operator=(BOOST_MOVE_BASE(tree_t, x))); }
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! <b>Effects</b>: Copy all elements from il to *this.
//!
//! <b>Complexity</b>: Linear in il.size().
flat_set& operator=(std::initializer_list<value_type> il)
{
this->clear();
this->insert(il.begin(), il.end());
return *this;
}
#endif
#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
//! <b>Effects</b>: Returns a copy of the allocator that
//! was passed to the object's constructor.
//!
//! <b>Complexity</b>: Constant.
allocator_type get_allocator() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a reference to the internal allocator.
//!
//! <b>Throws</b>: Nothing
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension.
stored_allocator_type &get_stored_allocator() BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a reference to the internal allocator.
//!
//! <b>Throws</b>: Nothing
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension.
const stored_allocator_type &get_stored_allocator() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns an iterator to the first element contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
iterator begin() BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a const_iterator to the first element contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_iterator begin() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns an iterator to the end of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
iterator end() BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a const_iterator to the end of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_iterator end() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a reverse_iterator pointing to the beginning
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
reverse_iterator rbegin() BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_reverse_iterator rbegin() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a reverse_iterator pointing to the end
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
reverse_iterator rend() BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_reverse_iterator rend() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a const_iterator to the first element contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_iterator cbegin() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a const_iterator to the end of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_iterator cend() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_reverse_iterator crbegin() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_reverse_iterator crend() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns true if the container contains no elements.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
bool empty() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns the number of the elements contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
size_type size() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns the largest possible size of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
size_type max_size() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Number of elements for which memory has been allocated.
//! capacity() is always greater than or equal to size().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
size_type capacity() const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: If n is less than or equal to capacity(), or the
//! underlying container has no `reserve` member, this call has no
//! effect. Otherwise, it is a request for allocation of additional memory.
//! If the request is successful, then capacity() is greater than or equal to
//! n; otherwise, capacity() is unchanged. In either case, size() is unchanged.
//!
//! <b>Throws</b>: If memory allocation allocation throws or T's copy constructor throws.
//!
//! <b>Note</b>: If capacity() is less than "cnt", iterators and references to
//! to values might be invalidated.
void reserve(size_type cnt);
//! <b>Effects</b>: Tries to deallocate the excess of memory created
// with previous allocations. The size of the vector is unchanged
//!
//! <b>Throws</b>: If memory allocation throws, or Key's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to size().
void shrink_to_fit();
#endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//////////////////////////////////////////////
//
// modifiers
//
//////////////////////////////////////////////
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts an object x of type Key constructed with
//! std::forward<Args>(args)... if and only if there is no element in the container
//! with key equivalent to the key of x.
//!
//! <b>Returns</b>: The bool component of the returned pair is true if and only
//! if the insertion takes place, and the iterator component of the pair
//! points to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time plus linear insertion
//! to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
template <class... Args>
BOOST_CONTAINER_FORCEINLINE std::pair<iterator,bool> emplace(BOOST_FWD_REF(Args)... args)
{ return this->tree_t::emplace_unique(boost::forward<Args>(args)...); }
//! <b>Effects</b>: Inserts an object of type Key constructed with
//! std::forward<Args>(args)... in the container if and only if there is
//! no element in the container with key equivalent to the key of x.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time (constant if x is inserted
//! right before p) plus insertion linear to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
template <class... Args>
BOOST_CONTAINER_FORCEINLINE iterator emplace_hint(const_iterator p, BOOST_FWD_REF(Args)... args)
{ return this->tree_t::emplace_hint_unique(p, boost::forward<Args>(args)...); }
#else // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#define BOOST_CONTAINER_FLAT_SET_EMPLACE_CODE(N) \
BOOST_MOVE_TMPL_LT##N BOOST_MOVE_CLASS##N BOOST_MOVE_GT##N \
BOOST_CONTAINER_FORCEINLINE std::pair<iterator,bool> emplace(BOOST_MOVE_UREF##N)\
{ return this->tree_t::emplace_unique(BOOST_MOVE_FWD##N); }\
\
BOOST_MOVE_TMPL_LT##N BOOST_MOVE_CLASS##N BOOST_MOVE_GT##N \
BOOST_CONTAINER_FORCEINLINE iterator emplace_hint(const_iterator hint BOOST_MOVE_I##N BOOST_MOVE_UREF##N)\
{ return this->tree_t::emplace_hint_unique(hint BOOST_MOVE_I##N BOOST_MOVE_FWD##N); }\
//
BOOST_MOVE_ITERATE_0TO9(BOOST_CONTAINER_FLAT_SET_EMPLACE_CODE)
#undef BOOST_CONTAINER_FLAT_SET_EMPLACE_CODE
#endif // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts x if and only if there is no element in the container
//! with key equivalent to the key of x.
//!
//! <b>Returns</b>: The bool component of the returned pair is true if and only
//! if the insertion takes place, and the iterator component of the pair
//! points to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time plus linear insertion
//! to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
std::pair<iterator, bool> insert(const value_type &x);
//! <b>Effects</b>: Inserts a new value_type move constructed from the pair if and
//! only if there is no element in the container with key equivalent to the key of x.
//!
//! <b>Returns</b>: The bool component of the returned pair is true if and only
//! if the insertion takes place, and the iterator component of the pair
//! points to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time plus linear insertion
//! to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
std::pair<iterator, bool> insert(value_type &&x);
#else
private:
typedef std::pair<iterator, bool> insert_return_pair;
public:
BOOST_MOVE_CONVERSION_AWARE_CATCH(insert, value_type, insert_return_pair, this->priv_insert)
#endif
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts a copy of x in the container if and only if there is
//! no element in the container with key equivalent to the key of x.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time (constant if x is inserted
//! right before p) plus insertion linear to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
iterator insert(const_iterator p, const value_type &x);
//! <b>Effects</b>: Inserts an element move constructed from x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time (constant if x is inserted
//! right before p) plus insertion linear to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
iterator insert(const_iterator p, value_type &&x);
#else
BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, value_type, iterator, this->priv_insert, const_iterator, const_iterator)
#endif
//! <b>Requires</b>: first, last are not iterators into *this.
//!
//! <b>Effects</b>: inserts each element from the range [first,last) if and only
//! if there is no element with key equivalent to the key of that element.
//!
//! <b>Complexity</b>: N log(N).
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE void insert(InputIterator first, InputIterator last)
{ this->tree_t::insert_unique(first, last); }
//! <b>Requires</b>: first, last are not iterators into *this and
//! must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Effects</b>: inserts each element from the range [first,last) .This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Complexity</b>: Linear.
//!
//! <b>Note</b>: Non-standard extension. If an element is inserted it might invalidate elements.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE void insert(ordered_unique_range_t, InputIterator first, InputIterator last)
{ this->tree_t::insert_unique(ordered_unique_range, first, last); }
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! <b>Effects</b>: inserts each element from the range [il.begin(), il.end()) if and only
//! if there is no element with key equivalent to the key of that element.
//!
//! <b>Complexity</b>: N log(N).
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
BOOST_CONTAINER_FORCEINLINE void insert(std::initializer_list<value_type> il)
{ this->tree_t::insert_unique(il.begin(), il.end()); }
//! <b>Requires</b>: Range [il.begin(), il.end()) must be ordered according to the predicate
//! and must be unique values.
//!
//! <b>Effects</b>: inserts each element from the range [il.begin(), il.end()) .This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Complexity</b>: Linear.
//!
//! <b>Note</b>: Non-standard extension. If an element is inserted it might invalidate elements.
BOOST_CONTAINER_FORCEINLINE void insert(ordered_unique_range_t, std::initializer_list<value_type> il)
{ this->tree_t::insert_unique(ordered_unique_range, il.begin(), il.end()); }
#endif
//! @copydoc ::boost::container::flat_map::merge(flat_map<Key, T, C2, AllocatorOrContainer>&)
template<class C2>
BOOST_CONTAINER_FORCEINLINE void merge(flat_set<Key, C2, AllocatorOrContainer>& source)
{ this->tree_t::merge_unique(source.tree()); }
//! @copydoc ::boost::container::flat_set::merge(flat_set<Key, C2, AllocatorOrContainer>&)
template<class C2>
BOOST_CONTAINER_FORCEINLINE void merge(BOOST_RV_REF_BEG flat_set<Key, C2, AllocatorOrContainer> BOOST_RV_REF_END source)
{ return this->merge(static_cast<flat_set<Key, C2, AllocatorOrContainer>&>(source)); }
//! @copydoc ::boost::container::flat_map::merge(flat_multimap<Key, T, C2, AllocatorOrContainer>&)
template<class C2>
BOOST_CONTAINER_FORCEINLINE void merge(flat_multiset<Key, C2, AllocatorOrContainer>& source)
{ this->tree_t::merge_unique(source.tree()); }
//! @copydoc ::boost::container::flat_set::merge(flat_multiset<Key, C2, AllocatorOrContainer>&)
template<class C2>
BOOST_CONTAINER_FORCEINLINE void merge(BOOST_RV_REF_BEG flat_multiset<Key, C2, AllocatorOrContainer> BOOST_RV_REF_END source)
{ return this->merge(static_cast<flat_multiset<Key, C2, AllocatorOrContainer>&>(source)); }
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Erases the element pointed to by p.
//!
//! <b>Returns</b>: Returns an iterator pointing to the element immediately
//! following q prior to the element being erased. If no such element exists,
//! returns end().
//!
//! <b>Complexity</b>: Linear to the elements with keys bigger than p
//!
//! <b>Note</b>: Invalidates elements with keys
//! not less than the erased element.
iterator erase(const_iterator p);
//! <b>Effects</b>: Erases all elements in the container with key equivalent to x.
//!
//! <b>Returns</b>: Returns the number of erased elements.
//!
//! <b>Complexity</b>: Logarithmic search time plus erasure time
//! linear to the elements with bigger keys.
size_type erase(const key_type& x);
//! <b>Effects</b>: Erases all the elements in the range [first, last).
//!
//! <b>Returns</b>: Returns last.
//!
//! <b>Complexity</b>: size()*N where N is the distance from first to last.
//!
//! <b>Complexity</b>: Logarithmic search time plus erasure time
//! linear to the elements with bigger keys.
iterator erase(const_iterator first, const_iterator last);
//! <b>Effects</b>: Swaps the contents of *this and x.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
void swap(flat_set& x)
BOOST_NOEXCEPT_IF( allocator_traits_type::is_always_equal::value
&& boost::container::dtl::is_nothrow_swappable<Compare>::value );
//! <b>Effects</b>: erase(a.begin(),a.end()).
//!
//! <b>Postcondition</b>: size() == 0.
//!
//! <b>Complexity</b>: linear in size().
void clear() BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Effects</b>: Returns the comparison object out
//! of which a was constructed.
//!
//! <b>Complexity</b>: Constant.
key_compare key_comp() const;
//! <b>Effects</b>: Returns an object of value_compare constructed out
//! of the comparison object.
//!
//! <b>Complexity</b>: Constant.
value_compare value_comp() const;
//! <b>Returns</b>: An iterator pointing to an element with the key
//! equivalent to x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic.
iterator find(const key_type& x);
//! <b>Returns</b>: A const_iterator pointing to an element with the key
//! equivalent to x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic.
const_iterator find(const key_type& x) const;
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Returns</b>: An iterator pointing to an element with the key
//! equivalent to x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic.
template<typename K>
iterator find(const K& x);
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Returns</b>: A const_iterator pointing to an element with the key
//! equivalent to x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic.
template<typename K>
const_iterator find(const K& x) const;
//! <b>Requires</b>: size() >= n.
//!
//! <b>Effects</b>: Returns an iterator to the nth element
//! from the beginning of the container. Returns end()
//! if n == size().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension
iterator nth(size_type n) BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Requires</b>: size() >= n.
//!
//! <b>Effects</b>: Returns a const_iterator to the nth element
//! from the beginning of the container. Returns end()
//! if n == size().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension
const_iterator nth(size_type n) const BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Requires</b>: begin() <= p <= end().
//!
//! <b>Effects</b>: Returns the index of the element pointed by p
//! and size() if p == end().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension
size_type index_of(iterator p) BOOST_NOEXCEPT_OR_NOTHROW;
//! <b>Requires</b>: begin() <= p <= end().
//!
//! <b>Effects</b>: Returns the index of the element pointed by p
//! and size() if p == end().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension
size_type index_of(const_iterator p) const BOOST_NOEXCEPT_OR_NOTHROW;
#endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Returns</b>: The number of elements with key equivalent to x.
//!
//! <b>Complexity</b>: log(size())+count(k)
BOOST_CONTAINER_FORCEINLINE size_type count(const key_type& x) const
{ return static_cast<size_type>(this->tree_t::find(x) != this->tree_t::cend()); }
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Returns</b>: The number of elements with key equivalent to x.
//!
//! <b>Complexity</b>: log(size())+count(k)
template<typename K>
BOOST_CONTAINER_FORCEINLINE size_type count(const K& x) const
{ return static_cast<size_type>(this->tree_t::find(x) != this->tree_t::cend()); }
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Returns</b>: Returns true if there is an element with key
//! equivalent to key in the container, otherwise false.
//!
//! <b>Complexity</b>: log(size()).
bool contains(const key_type& x) const;
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Returns</b>: Returns true if there is an element with key
//! equivalent to key in the container, otherwise false.
//!
//! <b>Complexity</b>: log(size()).
template<typename K>
bool contains(const K& x) const;
//! <b>Returns</b>: An iterator pointing to the first element with key not less
//! than k, or a.end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
iterator lower_bound(const key_type& x);
//! <b>Returns</b>: A const iterator pointing to the first element with key not
//! less than k, or a.end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
const_iterator lower_bound(const key_type& x) const;
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Returns</b>: An iterator pointing to the first element with key not less
//! than k, or a.end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
template<typename K>
iterator lower_bound(const K& x);
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Returns</b>: A const iterator pointing to the first element with key not
//! less than k, or a.end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
template<typename K>
const_iterator lower_bound(const K& x) const;
//! <b>Returns</b>: An iterator pointing to the first element with key not less
//! than x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
iterator upper_bound(const key_type& x);
//! <b>Returns</b>: A const iterator pointing to the first element with key not
//! less than x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
const_iterator upper_bound(const key_type& x) const;
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Returns</b>: An iterator pointing to the first element with key not less
//! than x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
template<typename K>
iterator upper_bound(const K& x);
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Returns</b>: A const iterator pointing to the first element with key not
//! less than x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
template<typename K>
const_iterator upper_bound(const K& x) const;
#endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)).
//!
//! <b>Complexity</b>: Logarithmic
BOOST_CONTAINER_FORCEINLINE std::pair<const_iterator, const_iterator> equal_range(const key_type& x) const
{ return this->tree_t::lower_bound_range(x); }
//! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)).
//!
//! <b>Complexity</b>: Logarithmic
BOOST_CONTAINER_FORCEINLINE std::pair<iterator,iterator> equal_range(const key_type& x)
{ return this->tree_t::lower_bound_range(x); }
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)).
//!
//! <b>Complexity</b>: Logarithmic
template<typename K>
std::pair<iterator,iterator> equal_range(const K& x)
{ return this->tree_t::lower_bound_range(x); }
//! <b>Requires</b>: This overload is available only if
//! key_compare::is_transparent exists.
//!
//! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)).
//!
//! <b>Complexity</b>: Logarithmic
template<typename K>
std::pair<const_iterator,const_iterator> equal_range(const K& x) const
{ return this->tree_t::lower_bound_range(x); }
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Returns true if x and y are equal
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator==(const flat_set& x, const flat_set& y);
//! <b>Effects</b>: Returns true if x and y are unequal
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator!=(const flat_set& x, const flat_set& y);
//! <b>Effects</b>: Returns true if x is less than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator<(const flat_set& x, const flat_set& y);
//! <b>Effects</b>: Returns true if x is greater than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator>(const flat_set& x, const flat_set& y);
//! <b>Effects</b>: Returns true if x is equal or less than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator<=(const flat_set& x, const flat_set& y);
//! <b>Effects</b>: Returns true if x is equal or greater than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator>=(const flat_set& x, const flat_set& y);
//! <b>Effects</b>: x.swap(y)
//!
//! <b>Complexity</b>: Constant.
friend void swap(flat_set& x, flat_set& y);
//! <b>Effects</b>: Extracts the internal sequence container.
//!
//! <b>Complexity</b>: Same as the move constructor of sequence_type, usually constant.
//!
//! <b>Postcondition</b>: this->empty()
//!
//! <b>Throws</b>: If secuence_type's move constructor throws
sequence_type extract_sequence();
#endif //#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
//! <b>Effects</b>: Discards the internally hold sequence container and adopts the
//! one passed externally using the move assignment. Erases non-unique elements.
//!
//! <b>Complexity</b>: Assuming O(1) move assignment, O(NlogN) with N = seq.size()
//!
//! <b>Throws</b>: If the comparison or the move constructor throws
BOOST_CONTAINER_FORCEINLINE void adopt_sequence(BOOST_RV_REF(sequence_type) seq)
{ this->tree_t::adopt_sequence_unique(boost::move(seq)); }
//! <b>Requires</b>: seq shall be ordered according to this->compare()
//! and shall contain unique elements.
//!
//! <b>Effects</b>: Discards the internally hold sequence container and adopts the
//! one passed externally using the move assignment.
//!
//! <b>Complexity</b>: Assuming O(1) move assignment, O(1)
//!
//! <b>Throws</b>: If the move assignment throws
BOOST_CONTAINER_FORCEINLINE void adopt_sequence(ordered_unique_range_t, BOOST_RV_REF(sequence_type) seq)
{ this->tree_t::adopt_sequence_unique(ordered_unique_range_t(), boost::move(seq)); }
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
private:
template<class KeyType>
BOOST_CONTAINER_FORCEINLINE std::pair<iterator, bool> priv_insert(BOOST_FWD_REF(KeyType) x)
{ return this->tree_t::insert_unique(::boost::forward<KeyType>(x)); }
template<class KeyType>
BOOST_CONTAINER_FORCEINLINE iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x)
{ return this->tree_t::insert_unique(p, ::boost::forward<KeyType>(x)); }
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
};
#ifndef BOOST_CONTAINER_NO_CXX17_CTAD
template <typename InputIterator>
flat_set(InputIterator, InputIterator) ->
flat_set< it_based_value_type_t<InputIterator> >;
template < typename InputIterator, typename AllocatorOrCompare>
flat_set(InputIterator, InputIterator, AllocatorOrCompare const&) ->
flat_set< it_based_value_type_t<InputIterator>
, typename dtl::if_c< // Compare
dtl::is_allocator<AllocatorOrCompare>::value
, std::less<it_based_value_type_t<InputIterator>>
, AllocatorOrCompare
>::type
, typename dtl::if_c< // Allocator
dtl::is_allocator<AllocatorOrCompare>::value
, AllocatorOrCompare
, new_allocator<it_based_value_type_t<InputIterator>>
>::type
>;
template < typename InputIterator, typename Compare, typename Allocator
, typename = dtl::require_nonallocator_t<Compare>
, typename = dtl::require_allocator_t<Allocator>>
flat_set(InputIterator, InputIterator, Compare const&, Allocator const&) ->
flat_set< it_based_value_type_t<InputIterator>
, Compare
, Allocator>;
template <typename InputIterator>
flat_set(ordered_unique_range_t, InputIterator, InputIterator) ->
flat_set< it_based_value_type_t<InputIterator>>;
template < typename InputIterator, typename AllocatorOrCompare>
flat_set(ordered_unique_range_t, InputIterator, InputIterator, AllocatorOrCompare const&) ->
flat_set< it_based_value_type_t<InputIterator>
, typename dtl::if_c< // Compare
dtl::is_allocator<AllocatorOrCompare>::value
, std::less<it_based_value_type_t<InputIterator>>
, AllocatorOrCompare
>::type
, typename dtl::if_c< // Allocator
dtl::is_allocator<AllocatorOrCompare>::value
, AllocatorOrCompare
, new_allocator<it_based_value_type_t<InputIterator>>
>::type
>;
template < typename InputIterator, typename Compare, typename Allocator
, typename = dtl::require_nonallocator_t<Compare>
, typename = dtl::require_allocator_t<Allocator>>
flat_set(ordered_unique_range_t, InputIterator, InputIterator, Compare const&, Allocator const&) ->
flat_set< it_based_value_type_t<InputIterator>
, Compare
, Allocator>;
#endif
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
} //namespace container {
//!has_trivial_destructor_after_move<> == true_type
//!specialization for optimizations
template <class Key, class Compare, class AllocatorOrContainer>
struct has_trivial_destructor_after_move<boost::container::flat_set<Key, Compare, AllocatorOrContainer> >
{
typedef typename ::boost::container::allocator_traits<AllocatorOrContainer>::pointer pointer;
static const bool value = ::boost::has_trivial_destructor_after_move<AllocatorOrContainer>::value &&
::boost::has_trivial_destructor_after_move<pointer>::value &&
::boost::has_trivial_destructor_after_move<Compare>::value;
};
namespace container {
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
//! flat_multiset is a Sorted Associative Container that stores objects of type Key and
//! can store multiple copies of the same key value.
//!
//! flat_multiset is similar to std::multiset but it's implemented by as an ordered sequence container.
//! The underlying sequence container is by default <i>vector</i> but it can also work
//! user-provided vector-like SequenceContainers (like <i>static_vector</i> or <i>small_vector</i>).
//!
//! Using vector-like sequence containers means that inserting a new element into a flat_multiset might invalidate
//! previous iterators and references (unless that sequence container is <i>stable_vector</i> or a similar
//! container that offers stable pointers and references). Similarly, erasing an element might invalidate
//! iterators and references pointing to elements that come after (their keys are bigger) the erased element.
//!
//! This container provides random-access iterators.
//!
//! \tparam Key is the type to be inserted in the multiset, which is also the key_type
//! \tparam Compare is the comparison functor used to order keys
//! \tparam AllocatorOrContainer is either:
//! - The allocator to allocate <code>value_type</code>s (e.g. <i>allocator< std::pair<Key, T> > </i>).
//! (in this case <i>sequence_type</i> will be vector<value_type, AllocatorOrContainer>)
//! - The SequenceContainer to be used as the underlying <i>sequence_type</i>. It must be a vector-like
//! sequence container with random-access iterators.
#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
template <class Key, class Compare = std::less<Key>, class AllocatorOrContainer = new_allocator<Key> >
#else
template <class Key, class Compare, class AllocatorOrContainer>
#endif
class flat_multiset
///@cond
: public dtl::flat_tree<Key, dtl::identity<Key>, Compare, AllocatorOrContainer>
///@endcond
{
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
private:
BOOST_COPYABLE_AND_MOVABLE(flat_multiset)
typedef dtl::flat_tree<Key, dtl::identity<Key>, Compare, AllocatorOrContainer> tree_t;
public:
tree_t &tree()
{ return *this; }
const tree_t &tree() const
{ return *this; }
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
public:
//////////////////////////////////////////////
//
// types
//
//////////////////////////////////////////////
typedef Key key_type;
typedef Compare key_compare;
typedef Key value_type;
typedef typename BOOST_CONTAINER_IMPDEF(tree_t::sequence_type) sequence_type;
typedef typename sequence_type::allocator_type allocator_type;
typedef ::boost::container::allocator_traits<allocator_type> allocator_traits_type;
typedef typename sequence_type::pointer pointer;
typedef typename sequence_type::const_pointer const_pointer;
typedef typename sequence_type::reference reference;
typedef typename sequence_type::const_reference const_reference;
typedef typename sequence_type::size_type size_type;
typedef typename sequence_type::difference_type difference_type;
typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type;
typedef typename BOOST_CONTAINER_IMPDEF(tree_t::value_compare) value_compare;
typedef typename sequence_type::iterator iterator;
typedef typename sequence_type::const_iterator const_iterator;
typedef typename sequence_type::reverse_iterator reverse_iterator;
typedef typename sequence_type::const_reverse_iterator const_reverse_iterator;
//! @copydoc ::boost::container::flat_set::flat_set()
BOOST_CONTAINER_FORCEINLINE flat_multiset() BOOST_NOEXCEPT_IF(dtl::is_nothrow_default_constructible<AllocatorOrContainer>::value &&
dtl::is_nothrow_default_constructible<Compare>::value)
: tree_t()
{}
//! @copydoc ::boost::container::flat_set::flat_set(const Compare&)
BOOST_CONTAINER_FORCEINLINE explicit flat_multiset(const Compare& comp)
: tree_t(comp)
{}
//! @copydoc ::boost::container::flat_set::flat_set(const allocator_type&)
BOOST_CONTAINER_FORCEINLINE explicit flat_multiset(const allocator_type& a)
: tree_t(a)
{}
//! @copydoc ::boost::container::flat_set::flat_set(const Compare&, const allocator_type&)
BOOST_CONTAINER_FORCEINLINE flat_multiset(const Compare& comp, const allocator_type& a)
: tree_t(comp, a)
{}
//! @copydoc ::boost::container::flat_set::flat_set(InputIterator, InputIterator)
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE flat_multiset(InputIterator first, InputIterator last)
: tree_t(false, first, last)
{}
//! @copydoc ::boost::container::flat_set::flat_set(InputIterator, InputIterator, const allocator_type&)
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE flat_multiset(InputIterator first, InputIterator last, const allocator_type& a)
: tree_t(false, first, last, a)
{}
//! @copydoc ::boost::container::flat_set::flat_set(InputIterator, InputIterator, const Compare& comp)
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE flat_multiset(InputIterator first, InputIterator last, const Compare& comp)
: tree_t(false, first, last, comp)
{}
//! @copydoc ::boost::container::flat_set::flat_set(InputIterator, InputIterator, const Compare& comp, const allocator_type&)
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE flat_multiset(InputIterator first, InputIterator last, const Compare& comp, const allocator_type& a)
: tree_t(false, first, last, comp, a)
{}
//! <b>Effects</b>: Constructs an empty flat_multiset and
//! inserts elements from the ordered range [first ,last ). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE flat_multiset(ordered_range_t, InputIterator first, InputIterator last)
: tree_t(ordered_range, first, last)
{}
//! <b>Effects</b>: Constructs an empty flat_multiset using the specified comparison object and
//! inserts elements from the ordered range [first ,last ). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE flat_multiset(ordered_range_t, InputIterator first, InputIterator last, const Compare& comp)
: tree_t(ordered_range, first, last, comp)
{}
//! <b>Effects</b>: Constructs an empty flat_multiset using the specified comparison object and
//! allocator, and inserts elements from the ordered range [first, last ). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE flat_multiset(ordered_range_t, InputIterator first, InputIterator last, const Compare& comp, const allocator_type& a)
: tree_t(ordered_range, first, last, comp, a)
{}
//! <b>Effects</b>: Constructs an empty flat_multiset using the specified allocator and
//! inserts elements from the ordered range [first ,last ). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE flat_multiset(ordered_range_t, InputIterator first, InputIterator last, const allocator_type &a)
: tree_t(ordered_range, first, last, Compare(), a)
{}
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! @copydoc ::boost::container::flat_set::flat_set(std::initializer_list<value_type)
BOOST_CONTAINER_FORCEINLINE flat_multiset(std::initializer_list<value_type> il)
: tree_t(false, il.begin(), il.end())
{}
//! @copydoc ::boost::container::flat_set::flat_set(std::initializer_list<value_type>, const allocator_type&)
BOOST_CONTAINER_FORCEINLINE flat_multiset(std::initializer_list<value_type> il, const allocator_type& a)
: tree_t(false, il.begin(), il.end(), a)
{}
//! @copydoc ::boost::container::flat_set::flat_set(std::initializer_list<value_type>, const Compare& comp)
BOOST_CONTAINER_FORCEINLINE flat_multiset(std::initializer_list<value_type> il, const Compare& comp)
: tree_t(false, il.begin(), il.end(), comp)
{}
//! @copydoc ::boost::container::flat_set::flat_set(std::initializer_list<value_type>, const Compare& comp, const allocator_type&)
BOOST_CONTAINER_FORCEINLINE flat_multiset(std::initializer_list<value_type> il, const Compare& comp, const allocator_type& a)
: tree_t(false, il.begin(), il.end(), comp, a)
{}
//! <b>Effects</b>: Constructs an empty containerand
//! inserts elements from the ordered unique range [il.begin(), il.end()). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [il.begin(), il.end()) must be ordered according to the predicate.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
BOOST_CONTAINER_FORCEINLINE flat_multiset(ordered_range_t, std::initializer_list<value_type> il)
: tree_t(ordered_range, il.begin(), il.end())
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! inserts elements from the ordered unique range [il.begin(), il.end()). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [il.begin(), il.end()) must be ordered according to the predicate.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
BOOST_CONTAINER_FORCEINLINE flat_multiset(ordered_range_t, std::initializer_list<value_type> il, const Compare& comp)
: tree_t(ordered_range, il.begin(), il.end(), comp)
{}
//! <b>Effects</b>: Constructs an empty container using the specified comparison object and
//! allocator, and inserts elements from the ordered unique range [il.begin(), il.end()). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [il.begin(), il.end()) must be ordered according to the predicate.
//!
//! <b>Complexity</b>: Linear in N.
//!
//! <b>Note</b>: Non-standard extension.
BOOST_CONTAINER_FORCEINLINE flat_multiset(ordered_range_t, std::initializer_list<value_type> il, const Compare& comp, const allocator_type& a)
: tree_t(ordered_range, il.begin(), il.end(), comp, a)
{}
#endif
//! @copydoc ::boost::container::flat_set::flat_set(const flat_set &)
BOOST_CONTAINER_FORCEINLINE flat_multiset(const flat_multiset& x)
: tree_t(static_cast<const tree_t&>(x))
{}
//! @copydoc ::boost::container::flat_set::flat_set(flat_set &&)
BOOST_CONTAINER_FORCEINLINE flat_multiset(BOOST_RV_REF(flat_multiset) x)
BOOST_NOEXCEPT_IF(boost::container::dtl::is_nothrow_move_constructible<Compare>::value)
: tree_t(boost::move(static_cast<tree_t&>(x)))
{}
//! @copydoc ::boost::container::flat_set::flat_set(const flat_set &, const allocator_type &)
BOOST_CONTAINER_FORCEINLINE flat_multiset(const flat_multiset& x, const allocator_type &a)
: tree_t(static_cast<const tree_t&>(x), a)
{}
//! @copydoc ::boost::container::flat_set::flat_set(flat_set &&, const allocator_type &)
BOOST_CONTAINER_FORCEINLINE flat_multiset(BOOST_RV_REF(flat_multiset) x, const allocator_type &a)
: tree_t(BOOST_MOVE_BASE(tree_t, x), a)
{}
//! @copydoc ::boost::container::flat_set::operator=(const flat_set &)
BOOST_CONTAINER_FORCEINLINE flat_multiset& operator=(BOOST_COPY_ASSIGN_REF(flat_multiset) x)
{ return static_cast<flat_multiset&>(this->tree_t::operator=(static_cast<const tree_t&>(x))); }
//! @copydoc ::boost::container::flat_set::operator=(flat_set &&)
BOOST_CONTAINER_FORCEINLINE flat_multiset& operator=(BOOST_RV_REF(flat_multiset) x)
BOOST_NOEXCEPT_IF( (allocator_traits_type::propagate_on_container_move_assignment::value ||
allocator_traits_type::is_always_equal::value) &&
boost::container::dtl::is_nothrow_move_assignable<Compare>::value)
{ return static_cast<flat_multiset&>(this->tree_t::operator=(BOOST_MOVE_BASE(tree_t, x))); }
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! @copydoc ::boost::container::flat_set::operator=(std::initializer_list<value_type>)
flat_multiset& operator=(std::initializer_list<value_type> il)
{
this->clear();
this->insert(il.begin(), il.end());
return *this;
}
#endif
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! @copydoc ::boost::container::flat_set::get_allocator()
allocator_type get_allocator() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::get_stored_allocator()
stored_allocator_type &get_stored_allocator() BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::get_stored_allocator() const
const stored_allocator_type &get_stored_allocator() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::begin()
iterator begin() BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::begin() const
const_iterator begin() const;
//! @copydoc ::boost::container::flat_set::cbegin() const
const_iterator cbegin() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::end()
iterator end() BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::end() const
const_iterator end() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::cend() const
const_iterator cend() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::rbegin()
reverse_iterator rbegin() BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::rbegin() const
const_reverse_iterator rbegin() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::crbegin() const
const_reverse_iterator crbegin() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::rend()
reverse_iterator rend() BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::rend() const
const_reverse_iterator rend() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::crend() const
const_reverse_iterator crend() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::empty() const
bool empty() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::size() const
size_type size() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::max_size() const
size_type max_size() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::capacity() const
size_type capacity() const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::reserve(size_type)
void reserve(size_type cnt);
//! @copydoc ::boost::container::flat_set::shrink_to_fit()
void shrink_to_fit();
#endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//////////////////////////////////////////////
//
// modifiers
//
//////////////////////////////////////////////
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts an object of type Key constructed with
//! std::forward<Args>(args)... and returns the iterator pointing to the
//! newly inserted element.
//!
//! <b>Complexity</b>: Logarithmic search time plus linear insertion
//! to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
template <class... Args>
BOOST_CONTAINER_FORCEINLINE iterator emplace(BOOST_FWD_REF(Args)... args)
{ return this->tree_t::emplace_equal(boost::forward<Args>(args)...); }
//! <b>Effects</b>: Inserts an object of type Key constructed with
//! std::forward<Args>(args)... in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time (constant if x is inserted
//! right before p) plus insertion linear to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
template <class... Args>
BOOST_CONTAINER_FORCEINLINE iterator emplace_hint(const_iterator p, BOOST_FWD_REF(Args)... args)
{ return this->tree_t::emplace_hint_equal(p, boost::forward<Args>(args)...); }
#else // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#define BOOST_CONTAINER_FLAT_MULTISET_EMPLACE_CODE(N) \
BOOST_MOVE_TMPL_LT##N BOOST_MOVE_CLASS##N BOOST_MOVE_GT##N \
BOOST_CONTAINER_FORCEINLINE iterator emplace(BOOST_MOVE_UREF##N)\
{ return this->tree_t::emplace_equal(BOOST_MOVE_FWD##N); }\
\
BOOST_MOVE_TMPL_LT##N BOOST_MOVE_CLASS##N BOOST_MOVE_GT##N \
BOOST_CONTAINER_FORCEINLINE iterator emplace_hint(const_iterator hint BOOST_MOVE_I##N BOOST_MOVE_UREF##N)\
{ return this->tree_t::emplace_hint_equal(hint BOOST_MOVE_I##N BOOST_MOVE_FWD##N); }\
//
BOOST_MOVE_ITERATE_0TO9(BOOST_CONTAINER_FLAT_MULTISET_EMPLACE_CODE)
#undef BOOST_CONTAINER_FLAT_MULTISET_EMPLACE_CODE
#endif // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts x and returns the iterator pointing to the
//! newly inserted element.
//!
//! <b>Complexity</b>: Logarithmic search time plus linear insertion
//! to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
iterator insert(const value_type &x);
//! <b>Effects</b>: Inserts a new value_type move constructed from x
//! and returns the iterator pointing to the newly inserted element.
//!
//! <b>Complexity</b>: Logarithmic search time plus linear insertion
//! to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
iterator insert(value_type &&x);
#else
BOOST_MOVE_CONVERSION_AWARE_CATCH(insert, value_type, iterator, this->priv_insert)
#endif
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts a copy of x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time (constant if x is inserted
//! right before p) plus insertion linear to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
iterator insert(const_iterator p, const value_type &x);
//! <b>Effects</b>: Inserts a new value move constructed from x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic search time (constant if x is inserted
//! right before p) plus insertion linear to the elements with bigger keys than x.
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
iterator insert(const_iterator p, value_type &&x);
#else
BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, value_type, iterator, this->priv_insert, const_iterator, const_iterator)
#endif
//! <b>Requires</b>: first, last are not iterators into *this.
//!
//! <b>Effects</b>: inserts each element from the range [first,last) .
//!
//! <b>Complexity</b>: N log(N).
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE void insert(InputIterator first, InputIterator last)
{ this->tree_t::insert_equal(first, last); }
//! <b>Requires</b>: first, last are not iterators into *this and
//! must be ordered according to the predicate.
//!
//! <b>Effects</b>: inserts each element from the range [first,last) .This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Complexity</b>: Linear.
//!
//! <b>Note</b>: Non-standard extension. If an element is inserted it might invalidate elements.
template <class InputIterator>
BOOST_CONTAINER_FORCEINLINE void insert(ordered_range_t, InputIterator first, InputIterator last)
{ this->tree_t::insert_equal(ordered_range, first, last); }
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! <b>Effects</b>: inserts each element from the range [il.begin(), il.end()).
//!
//! <b>Complexity</b>: N log(N).
//!
//! <b>Note</b>: If an element is inserted it might invalidate elements.
BOOST_CONTAINER_FORCEINLINE void insert(std::initializer_list<value_type> il)
{ this->tree_t::insert_equal(il.begin(), il.end()); }
//! <b>Requires</b>: Range [il.begin(), il.end()) must be ordered according to the predicate.
//!
//! <b>Effects</b>: inserts each element from the range [il.begin(), il.end()). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Complexity</b>: Linear.
//!
//! <b>Note</b>: Non-standard extension. If an element is inserted it might invalidate elements.
BOOST_CONTAINER_FORCEINLINE void insert(ordered_range_t, std::initializer_list<value_type> il)
{ this->tree_t::insert_equal(ordered_range, il.begin(), il.end()); }
#endif
//! @copydoc ::boost::container::flat_multimap::merge(flat_multimap<Key, T, C2, AllocatorOrContainer>&)
template<class C2>
BOOST_CONTAINER_FORCEINLINE void merge(flat_multiset<Key, C2, AllocatorOrContainer>& source)
{ this->tree_t::merge_equal(source.tree()); }
//! @copydoc ::boost::container::flat_multiset::merge(flat_multiset<Key, C2, AllocatorOrContainer>&)
template<class C2>
BOOST_CONTAINER_FORCEINLINE void merge(BOOST_RV_REF_BEG flat_multiset<Key, C2, AllocatorOrContainer> BOOST_RV_REF_END source)
{ return this->merge(static_cast<flat_multiset<Key, C2, AllocatorOrContainer>&>(source)); }
//! @copydoc ::boost::container::flat_multimap::merge(flat_map<Key, T, C2, AllocatorOrContainer>&)
template<class C2>
BOOST_CONTAINER_FORCEINLINE void merge(flat_set<Key, C2, AllocatorOrContainer>& source)
{ this->tree_t::merge_equal(source.tree()); }
//! @copydoc ::boost::container::flat_multiset::merge(flat_set<Key, C2, AllocatorOrContainer>&)
template<class C2>
BOOST_CONTAINER_FORCEINLINE void merge(BOOST_RV_REF_BEG flat_set<Key, C2, AllocatorOrContainer> BOOST_RV_REF_END source)
{ return this->merge(static_cast<flat_set<Key, C2, AllocatorOrContainer>&>(source)); }
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! @copydoc ::boost::container::flat_set::erase(const_iterator)
iterator erase(const_iterator p);
//! @copydoc ::boost::container::flat_set::erase(const key_type&)
size_type erase(const key_type& x);
//! @copydoc ::boost::container::flat_set::erase(const_iterator,const_iterator)
iterator erase(const_iterator first, const_iterator last);
//! @copydoc ::boost::container::flat_set::swap
void swap(flat_multiset& x)
BOOST_NOEXCEPT_IF( allocator_traits_type::is_always_equal::value
&& boost::container::dtl::is_nothrow_swappable<Compare>::value );
//! @copydoc ::boost::container::flat_set::clear
void clear() BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::key_comp
key_compare key_comp() const;
//! @copydoc ::boost::container::flat_set::value_comp
value_compare value_comp() const;
//! @copydoc ::boost::container::flat_set::find(const key_type& )
iterator find(const key_type& x);
//! @copydoc ::boost::container::flat_set::find(const key_type& ) const
const_iterator find(const key_type& x) const;
//! @copydoc ::boost::container::flat_set::nth(size_type)
iterator nth(size_type n) BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::nth(size_type) const
const_iterator nth(size_type n) const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::index_of(iterator)
size_type index_of(iterator p) BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::index_of(const_iterator) const
size_type index_of(const_iterator p) const BOOST_NOEXCEPT_OR_NOTHROW;
//! @copydoc ::boost::container::flat_set::count(const key_type& ) const
size_type count(const key_type& x) const;
//! @copydoc ::boost::container::flat_set::contains(const key_type& ) const
bool contains(const key_type& x) const;
//! @copydoc ::boost::container::flat_set::contains(const K& ) const
template<typename K>
bool contains(const K& x) const;
//! @copydoc ::boost::container::flat_set::lower_bound(const key_type& )
iterator lower_bound(const key_type& x);
//! @copydoc ::boost::container::flat_set::lower_bound(const key_type& ) const
const_iterator lower_bound(const key_type& x) const;
//! @copydoc ::boost::container::flat_set::upper_bound(const key_type& )
iterator upper_bound(const key_type& x);
//! @copydoc ::boost::container::flat_set::upper_bound(const key_type& ) const
const_iterator upper_bound(const key_type& x) const;
//! @copydoc ::boost::container::flat_set::equal_range(const key_type& ) const
std::pair<const_iterator, const_iterator> equal_range(const key_type& x) const;
//! @copydoc ::boost::container::flat_set::equal_range(const key_type& )
std::pair<iterator,iterator> equal_range(const key_type& x);
//! <b>Effects</b>: Returns true if x and y are equal
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator==(const flat_multiset& x, const flat_multiset& y);
//! <b>Effects</b>: Returns true if x and y are unequal
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator!=(const flat_multiset& x, const flat_multiset& y);
//! <b>Effects</b>: Returns true if x is less than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator<(const flat_multiset& x, const flat_multiset& y);
//! <b>Effects</b>: Returns true if x is greater than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator>(const flat_multiset& x, const flat_multiset& y);
//! <b>Effects</b>: Returns true if x is equal or less than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator<=(const flat_multiset& x, const flat_multiset& y);
//! <b>Effects</b>: Returns true if x is equal or greater than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
friend bool operator>=(const flat_multiset& x, const flat_multiset& y);
//! <b>Effects</b>: x.swap(y)
//!
//! <b>Complexity</b>: Constant.
friend void swap(flat_multiset& x, flat_multiset& y);
//! <b>Effects</b>: Extracts the internal sequence container.
//!
//! <b>Complexity</b>: Same as the move constructor of sequence_type, usually constant.
//!
//! <b>Postcondition</b>: this->empty()
//!
//! <b>Throws</b>: If secuence_type's move constructor throws
sequence_type extract_sequence();
#endif //#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
//! <b>Effects</b>: Discards the internally hold sequence container and adopts the
//! one passed externally using the move assignment.
//!
//! <b>Complexity</b>: Assuming O(1) move assignment, O(NlogN) with N = seq.size()
//!
//! <b>Throws</b>: If the comparison or the move constructor throws
BOOST_CONTAINER_FORCEINLINE void adopt_sequence(BOOST_RV_REF(sequence_type) seq)
{ this->tree_t::adopt_sequence_equal(boost::move(seq)); }
//! <b>Requires</b>: seq shall be ordered according to this->compare()
//!
//! <b>Effects</b>: Discards the internally hold sequence container and adopts the
//! one passed externally using the move assignment.
//!
//! <b>Complexity</b>: Assuming O(1) move assignment, O(1)
//!
//! <b>Throws</b>: If the move assignment throws
BOOST_CONTAINER_FORCEINLINE void adopt_sequence(ordered_range_t, BOOST_RV_REF(sequence_type) seq)
{ this->tree_t::adopt_sequence_equal(ordered_range_t(), boost::move(seq)); }
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
private:
template <class KeyType>
BOOST_CONTAINER_FORCEINLINE iterator priv_insert(BOOST_FWD_REF(KeyType) x)
{ return this->tree_t::insert_equal(::boost::forward<KeyType>(x)); }
template <class KeyType>
BOOST_CONTAINER_FORCEINLINE iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x)
{ return this->tree_t::insert_equal(p, ::boost::forward<KeyType>(x)); }
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
};
#ifndef BOOST_CONTAINER_NO_CXX17_CTAD
template <typename InputIterator>
flat_multiset(InputIterator, InputIterator) ->
flat_multiset< it_based_value_type_t<InputIterator> >;
template < typename InputIterator, typename AllocatorOrCompare>
flat_multiset(InputIterator, InputIterator, AllocatorOrCompare const&) ->
flat_multiset < it_based_value_type_t<InputIterator>
, typename dtl::if_c< // Compare
dtl::is_allocator<AllocatorOrCompare>::value
, std::less<it_based_value_type_t<InputIterator>>
, AllocatorOrCompare
>::type
, typename dtl::if_c< // Allocator
dtl::is_allocator<AllocatorOrCompare>::value
, AllocatorOrCompare
, new_allocator<it_based_value_type_t<InputIterator>>
>::type
>;
template < typename InputIterator, typename Compare, typename Allocator
, typename = dtl::require_nonallocator_t<Compare>
, typename = dtl::require_allocator_t<Allocator>>
flat_multiset(InputIterator, InputIterator, Compare const&, Allocator const&) ->
flat_multiset< it_based_value_type_t<InputIterator>
, Compare
, Allocator>;
template <typename InputIterator>
flat_multiset(ordered_range_t, InputIterator, InputIterator) ->
flat_multiset< it_based_value_type_t<InputIterator>>;
template < typename InputIterator, typename AllocatorOrCompare>
flat_multiset(ordered_range_t, InputIterator, InputIterator, AllocatorOrCompare const&) ->
flat_multiset < it_based_value_type_t<InputIterator>
, typename dtl::if_c< // Compare
dtl::is_allocator<AllocatorOrCompare>::value
, std::less<it_based_value_type_t<InputIterator>>
, AllocatorOrCompare
>::type
, typename dtl::if_c< // Allocator
dtl::is_allocator<AllocatorOrCompare>::value
, AllocatorOrCompare
, new_allocator<it_based_value_type_t<InputIterator>>
>::type
>;
template < typename InputIterator, typename Compare, typename Allocator
, typename = dtl::require_nonallocator_t<Compare>
, typename = dtl::require_allocator_t<Allocator>>
flat_multiset(ordered_range_t, InputIterator, InputIterator, Compare const&, Allocator const&) ->
flat_multiset< it_based_value_type_t<InputIterator>
, Compare
, Allocator>;
#endif
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
} //namespace container {
//!has_trivial_destructor_after_move<> == true_type
//!specialization for optimizations
template <class Key, class Compare, class AllocatorOrContainer>
struct has_trivial_destructor_after_move<boost::container::flat_multiset<Key, Compare, AllocatorOrContainer> >
{
typedef typename ::boost::container::allocator_traits<AllocatorOrContainer>::pointer pointer;
static const bool value = ::boost::has_trivial_destructor_after_move<AllocatorOrContainer>::value &&
::boost::has_trivial_destructor_after_move<pointer>::value &&
::boost::has_trivial_destructor_after_move<Compare>::value;
};
namespace container {
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
}}
#include <boost/container/detail/config_end.hpp>
#endif // BOOST_CONTAINER_FLAT_SET_HPP
|
; A146884: Sum of power terms sequence: a(n)=Sum[7*6^m, {m, 0, n}].
; 7,49,301,1813,10885,65317,391909,2351461,14108773,84652645,507915877,3047495269,18284971621,109709829733,658258978405,3949553870437,23697323222629,142183939335781,853103636014693,5118621816088165
mov $1,6
pow $1,$0
div $1,5
mul $1,42
add $1,7
mov $0,$1
|
;
; $Id: 0x1d.asm,v 1.1.1.1 2016/03/27 08:40:12 raptor Exp $
;
; 0x1d explanation - from xchg rax,rax by xorpd@xorpd.net
; Copyright (c) 2016 Marco Ivaldi <raptor@0xdeadbeef.info>
;
; This snippet illustrates the enter instruction, which is
; commonly used together with its companion leave to
; support block structured programming languages (such as
; C): enter is typically the first instruction in a
; procedure and is used to set up a new stack frame; leave
; is used at the end of the procedure (just before the ret
; instruction) to release such stack frame.
; The "enter 0,n+1" instruction creates a stack frame for
; a procedure with a dynamic storage of 0 bytes and a
; lexical nesting level of n+1. The nesting level
; determines the number of frame pointers that are copied
; into the display area of the new stack frame from the
; preceding frame.
;
; If the nesting level is 0, the processor pushes the
; frame pointer (rbp) onto the stack, copies the current
; stack pointer (rsp) into rbp, and loads the rsp register
; with the current stack pointer value minus the value in
; the size operand (which is zero in this snippet). For
; nesting levels of 1 or greater, the processor pushes
; additional frame pointers on the stack before adjusting
; the stack pointer.
;
; That being said, this snippet looks like a convoluted
; way to copy the content of buff1 into buff2 for values
; of n of 1 or greater. See below for a few annotated gdb
; runs.
;
; $ gdb 0x1d # n=0
; (gdb) disas main
; Dump of assembler code for function main:
; 0x00000000004005f0 <+0>: movabs $0x6009fd,%rsp
; 0x00000000004005fa <+10>: movabs $0x6009f0,%rbp
; 0x0000000000400604 <+20>: enterq $0x0,$0x1
; 0x0000000000400608 <+24>: nopl 0x0(%rax,%rax,1)
; End of assembler dump.
; (gdb) b*0x00000000004005fa
; Breakpoint 1 at 0x4005fa
; (gdb) b*0x0000000000400604
; Breakpoint 2 at 0x400604
; (gdb) b*0x0000000000400608
; Breakpoint 3 at 0x400608
; (gdb) r
; Breakpoint 1, 0x00000000004005fa in main ()
; (gdb) i r rsp rbp
; rsp 0x6009fd 0x6009fd
; rbp 0x0 0x0
; (gdb) c
; Breakpoint 2, 0x0000000000400604 in main ()
; (gdb) i r rsp rbp
; rsp 0x6009fd 0x6009fd
; rbp 0x6009f0 0x6009f0
; (gdb) x/x 0x6009fd-8
; 0x6009f5: 0x42424242 <- buff2 is at 0x6009f5
; (gdb) x/x 0x6009f0
; 0x6009f0: 0x41414141 <- buff1 is at 0x6009f0
; (gdb) c
; Breakpoint 3, 0x0000000000400608 in main ()
; (gdb) i r rsp rbp
; rsp 0x6009ed 0x6009ed
; rbp 0x6009f5 0x6009f5
; (gdb) p/d 0x6009f5-0x6009f0
; $1 = 5
; (gdb) p/d 0x6009ed-0x6009fd <- sub rsp,(n+1)*8 + 8
; $2 = -16
; (gdb) c
; Program received signal SIGSEGV, Segmentation fault.
; 0x00000000006009f5 in buff2 ()
; (gdb) x/x 0x6009f5
; 0x6009f5: 0x006009f0 <- ???
; (gdb) x/x 0x6009f0
; 0x6009f0: 0x00000000 <- ???
;
; $ gdb 0x1d # n=1
; [...]
; Breakpoint 2, 0x0000000000400604 in main ()
; (gdb) i r rsp rbp
; rsp 0x600a05 0x600a05
; rbp 0x6009f8 0x6009f8
; (gdb) c
; Breakpoint 3, 0x0000000000400608 in main ()
; (gdb) i r rsp rbp
; rsp 0x6009ed 0x6009ed
; rbp 0x6009fd 0x6009fd
; (gdb) p/d 0x6009fd-0x6009f8
; $1 = 5
; (gdb) p/d 0x6009ed-0x600a05 <- sub rsp,(n+1)*8 + 8
; $2 = -24
; (gdb) c
; Program received signal SIGSEGV, Segmentation fault.
; 0x00000000006009fe in ?? ()
; (gdb) i r rsp rbp
; rsp 0x6009f5 0x6009f5
; rbp 0x6009fd 0x6009fd
; (gdb) x/x 0x6009f5
; 0x6009f5: 0x41414141 <- buff2 contains the string that used to be in buff1
;
; $ gdb 0x1d # n=2
; [...]
; Breakpoint 2, 0x0000000000400604 in main ()
; (gdb) i r rsp rbp
; rsp 0x600a0d 0x600a0d <dtor_idx.6364+5>
; rbp 0x600a00 0x600a00 <completed.6362>
; (gdb) x/x 0x600a0d-24
; 0x6009f5: 0x42424242 <- buff2 is at 0x6009f5
; (gdb) x/x 0x600a00-16
; 0x6009f0: 0x41414141 <- buff1 is at 0x6009f0
; (gdb) c
; Breakpoint 3, 0x0000000000400608 in main ()
; (gdb) i r rsp rbp
; rsp 0x6009ed 0x6009ed
; rbp 0x600a05 0x600a05
; (gdb) p/d 0x600a05-0x600a00
; $1 = 5
; (gdb) p/d 0x6009ed-0x600a0d <- sub rsp,(n+1)*8 + 8
; $2 = -32
; (gdb) x/x 0x600a05
; 0x600a05: 0x00600a0
; (gdb) x/x 0x6009ed
; 0x6009ed: 0x00600a05
; Program received signal SIGSEGV, Segmentation fault.
; 0x0000000000600a05 in ?? ()
; (gdb) i r rsp rbp
; rsp 0x6009f5 0x6009f5
; rbp 0x600a05 0x600a05
; (gdb) x/x 0x6009f5
; 0x6009f5: 0x41414141 <- buff2 contains the string that used to be in buff1
;
BITS 64
;%assign n 1 ; added for the analysis
;SECTION .data ; added for the analysis
;buff1 db "AAAA",0 ; added for the analysis
;buff2 db "BBBB",0 ; added for the analysis
SECTION .text
global main
main:
mov rsp,buff2 + n*8 + 8 ; load the address of buff2 + n*8 + 8
; into the stack pointer (rsp)
mov rbp,buff1 + n*8 ; load the address of buff1 + n*8
; into the base pointer (rbp)
enter 0,n+1 ; push rbp [i.e.: buff1 + n*8]
; mov rbp,rsp [i.e.: buff2 + n*8 + 8]
; [push n+1 additional frame pointers]
; sub rsp,(n+1)*8 + 8
|
/* **********************************************************
* Copyright (c) 2015 Google, Inc. All rights reserved.
* **********************************************************/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Google, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include "configure.h"
#include "../../../core/unix/include/syscall.h"
.global _start
_start:
// MMX instr
emms
// SSE instr
addps xmm0, xmm1
// SSE2 instr
pavgb xmm0, xmm1
// SSE3 instr
haddps xmm0, xmm1
// SSSE3 instr
phsubw xmm0, xmm1
// SSE4.1 instr
pblendvb xmm0, xmm1
// exit
mov eax, SYS_exit
#ifdef X64
syscall
#else
int 0x80
#endif
|
; A161712: a(n) = (4*n^3 - 6*n^2 + 8*n + 3)/3.
; 1,3,9,27,65,131,233,379,577,835,1161,1563,2049,2627,3305,4091,4993,6019,7177,8475,9921,11523,13289,15227,17345,19651,22153,24859,27777,30915,34281,37883,41729,45827,50185,54811,59713,64899,70377,76155,82241,88643,95369,102427,109825,117571,125673,134139,142977,152195,161801,171803,182209,193027,204265,215931,228033,240579,253577,267035,280961,295363,310249,325627,341505,357891,374793,392219,410177,428675,447721,467323,487489,508227,529545,551451,573953,597059,620777,645115,670081,695683,721929
mul $0,2
mov $1,$0
add $0,1
bin $1,3
add $0,$1
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// Unit tests for datatype.
#include <vespa/document/base/field.h>
#include <vespa/document/datatype/arraydatatype.h>
#include <vespa/document/datatype/structdatatype.h>
#include <vespa/document/datatype/tensor_data_type.h>
#include <vespa/document/fieldvalue/longfieldvalue.h>
#include <vespa/eval/eval/value_type.h>
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/exceptions.h>
using namespace document;
namespace {
template <typename S>
void assign(S &lhs, const S &rhs) {
lhs = rhs;
}
TEST("require that ArrayDataType can be assigned to.") {
ArrayDataType type1(*DataType::STRING);
ArrayDataType type2(*DataType::INT);
assign(type1, type1);
EXPECT_EQUAL(*DataType::STRING, type1.getNestedType());
type1 = type2;
EXPECT_EQUAL(*DataType::INT, type1.getNestedType());
}
TEST("require that ArrayDataType can be cloned.") {
ArrayDataType type1(*DataType::STRING);
std::unique_ptr<ArrayDataType> type2(type1.clone());
ASSERT_TRUE(type2.get());
EXPECT_EQUAL(*DataType::STRING, type2->getNestedType());
}
TEST("require that assignment operator works for LongFieldValue") {
LongFieldValue val;
val = "1";
EXPECT_EQUAL(1, val.getValue());
val = 2;
EXPECT_EQUAL(2, val.getValue());
val = static_cast<int64_t>(3);
EXPECT_EQUAL(3, val.getValue());
val = 4.0f;
EXPECT_EQUAL(4, val.getValue());
val = 5.0;
EXPECT_EQUAL(5, val.getValue());
}
TEST("require that StructDataType can redeclare identical fields.") {
StructDataType s("foo");
Field field1("field1", 42, *DataType::STRING, true);
Field field2("field2", 42, *DataType::STRING, true);
s.addField(field1);
s.addField(field1); // ok
s.addInheritedField(field1); // ok
EXPECT_EXCEPTION(s.addField(field2), vespalib::IllegalArgumentException,
"Field id in use by field Field(field1");
s.addInheritedField(field2);
EXPECT_FALSE(s.hasField(field2.getName()));
}
class TensorDataTypeFixture {
std::unique_ptr<const TensorDataType> _tensorDataType;
public:
using ValueType = vespalib::eval::ValueType;
TensorDataTypeFixture()
: _tensorDataType()
{
}
~TensorDataTypeFixture();
void setup(const vespalib::string &spec)
{
_tensorDataType = TensorDataType::fromSpec(spec);
}
bool isAssignableType(const vespalib::string &spec) const
{
auto assignType = ValueType::from_spec(spec);
return _tensorDataType->isAssignableType(assignType);
}
};
TensorDataTypeFixture::~TensorDataTypeFixture() = default;
TEST_F("require that TensorDataType can check for assignable tensor type", TensorDataTypeFixture)
{
f.setup("tensor(x[2])");
EXPECT_TRUE(f.isAssignableType("tensor(x[2])"));
EXPECT_FALSE(f.isAssignableType("tensor(x[3])"));
EXPECT_FALSE(f.isAssignableType("tensor(y[2])"));
EXPECT_FALSE(f.isAssignableType("tensor(x{})"));
}
} // namespace
TEST_MAIN() { TEST_RUN_ALL(); }
|
_tracetest: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
#include "fcntl.h"
#include "syscall.h"
#include "traps.h"
#include "memlayout.h"
int main(int argc, char *argv[]){
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 51 push %ecx
e: 83 ec 04 sub $0x4,%esp
printf(1, "\nFirst test print ever\n");
11: 83 ec 08 sub $0x8,%esp
14: 68 5f 09 00 00 push $0x95f
19: 6a 01 push $0x1
1b: e8 8b 05 00 00 call 5ab <printf>
20: 83 c4 10 add $0x10,%esp
trace(1);
23: 83 ec 0c sub $0xc,%esp
26: 6a 01 push $0x1
28: e8 a1 04 00 00 call 4ce <trace>
2d: 83 c4 10 add $0x10,%esp
trace(1);
30: 83 ec 0c sub $0xc,%esp
33: 6a 01 push $0x1
35: e8 94 04 00 00 call 4ce <trace>
3a: 83 c4 10 add $0x10,%esp
trace(1);
3d: 83 ec 0c sub $0xc,%esp
40: 6a 01 push $0x1
42: e8 87 04 00 00 call 4ce <trace>
47: 83 c4 10 add $0x10,%esp
printf(1, "for the zeroeth test %d", trace(0));
4a: 83 ec 0c sub $0xc,%esp
4d: 6a 00 push $0x0
4f: e8 7a 04 00 00 call 4ce <trace>
54: 83 c4 10 add $0x10,%esp
57: 83 ec 04 sub $0x4,%esp
5a: 50 push %eax
5b: 68 77 09 00 00 push $0x977
60: 6a 01 push $0x1
62: e8 44 05 00 00 call 5ab <printf>
67: 83 c4 10 add $0x10,%esp
trace(1);
6a: 83 ec 0c sub $0xc,%esp
6d: 6a 01 push $0x1
6f: e8 5a 04 00 00 call 4ce <trace>
74: 83 c4 10 add $0x10,%esp
trace(1);
77: 83 ec 0c sub $0xc,%esp
7a: 6a 01 push $0x1
7c: e8 4d 04 00 00 call 4ce <trace>
81: 83 c4 10 add $0x10,%esp
trace(1);
84: 83 ec 0c sub $0xc,%esp
87: 6a 01 push $0x1
89: e8 40 04 00 00 call 4ce <trace>
8e: 83 c4 10 add $0x10,%esp
printf(1, "for the zeroeth test %d", trace(0));
91: 83 ec 0c sub $0xc,%esp
94: 6a 00 push $0x0
96: e8 33 04 00 00 call 4ce <trace>
9b: 83 c4 10 add $0x10,%esp
9e: 83 ec 04 sub $0x4,%esp
a1: 50 push %eax
a2: 68 77 09 00 00 push $0x977
a7: 6a 01 push $0x1
a9: e8 fd 04 00 00 call 5ab <printf>
ae: 83 c4 10 add $0x10,%esp
trace(1);
b1: 83 ec 0c sub $0xc,%esp
b4: 6a 01 push $0x1
b6: e8 13 04 00 00 call 4ce <trace>
bb: 83 c4 10 add $0x10,%esp
trace(1);
be: 83 ec 0c sub $0xc,%esp
c1: 6a 01 push $0x1
c3: e8 06 04 00 00 call 4ce <trace>
c8: 83 c4 10 add $0x10,%esp
trace(1);
cb: 83 ec 0c sub $0xc,%esp
ce: 6a 01 push $0x1
d0: e8 f9 03 00 00 call 4ce <trace>
d5: 83 c4 10 add $0x10,%esp
trace(1);
d8: 83 ec 0c sub $0xc,%esp
db: 6a 01 push $0x1
dd: e8 ec 03 00 00 call 4ce <trace>
e2: 83 c4 10 add $0x10,%esp
printf(1, "for the first test %d", trace(0));
e5: 83 ec 0c sub $0xc,%esp
e8: 6a 00 push $0x0
ea: e8 df 03 00 00 call 4ce <trace>
ef: 83 c4 10 add $0x10,%esp
f2: 83 ec 04 sub $0x4,%esp
f5: 50 push %eax
f6: 68 8f 09 00 00 push $0x98f
fb: 6a 01 push $0x1
fd: e8 a9 04 00 00 call 5ab <printf>
102: 83 c4 10 add $0x10,%esp
trace(1);
105: 83 ec 0c sub $0xc,%esp
108: 6a 01 push $0x1
10a: e8 bf 03 00 00 call 4ce <trace>
10f: 83 c4 10 add $0x10,%esp
trace(1);
112: 83 ec 0c sub $0xc,%esp
115: 6a 01 push $0x1
117: e8 b2 03 00 00 call 4ce <trace>
11c: 83 c4 10 add $0x10,%esp
trace(1);
11f: 83 ec 0c sub $0xc,%esp
122: 6a 01 push $0x1
124: e8 a5 03 00 00 call 4ce <trace>
129: 83 c4 10 add $0x10,%esp
trace(1);
12c: 83 ec 0c sub $0xc,%esp
12f: 6a 01 push $0x1
131: e8 98 03 00 00 call 4ce <trace>
136: 83 c4 10 add $0x10,%esp
trace(1);
139: 83 ec 0c sub $0xc,%esp
13c: 6a 01 push $0x1
13e: e8 8b 03 00 00 call 4ce <trace>
143: 83 c4 10 add $0x10,%esp
printf(1, "for the second test %d", trace(0));
146: 83 ec 0c sub $0xc,%esp
149: 6a 00 push $0x0
14b: e8 7e 03 00 00 call 4ce <trace>
150: 83 c4 10 add $0x10,%esp
153: 83 ec 04 sub $0x4,%esp
156: 50 push %eax
157: 68 a5 09 00 00 push $0x9a5
15c: 6a 01 push $0x1
15e: e8 48 04 00 00 call 5ab <printf>
163: 83 c4 10 add $0x10,%esp
trace(1);
166: 83 ec 0c sub $0xc,%esp
169: 6a 01 push $0x1
16b: e8 5e 03 00 00 call 4ce <trace>
170: 83 c4 10 add $0x10,%esp
trace(1);
173: 83 ec 0c sub $0xc,%esp
176: 6a 01 push $0x1
178: e8 51 03 00 00 call 4ce <trace>
17d: 83 c4 10 add $0x10,%esp
trace(1);
180: 83 ec 0c sub $0xc,%esp
183: 6a 01 push $0x1
185: e8 44 03 00 00 call 4ce <trace>
18a: 83 c4 10 add $0x10,%esp
trace(1);
18d: 83 ec 0c sub $0xc,%esp
190: 6a 01 push $0x1
192: e8 37 03 00 00 call 4ce <trace>
197: 83 c4 10 add $0x10,%esp
trace(1);
19a: 83 ec 0c sub $0xc,%esp
19d: 6a 01 push $0x1
19f: e8 2a 03 00 00 call 4ce <trace>
1a4: 83 c4 10 add $0x10,%esp
trace(1);
1a7: 83 ec 0c sub $0xc,%esp
1aa: 6a 01 push $0x1
1ac: e8 1d 03 00 00 call 4ce <trace>
1b1: 83 c4 10 add $0x10,%esp
printf(1, "for the third test %d", trace(0));
1b4: 83 ec 0c sub $0xc,%esp
1b7: 6a 00 push $0x0
1b9: e8 10 03 00 00 call 4ce <trace>
1be: 83 c4 10 add $0x10,%esp
1c1: 83 ec 04 sub $0x4,%esp
1c4: 50 push %eax
1c5: 68 bc 09 00 00 push $0x9bc
1ca: 6a 01 push $0x1
1cc: e8 da 03 00 00 call 5ab <printf>
1d1: 83 c4 10 add $0x10,%esp
exit();
1d4: e8 55 02 00 00 call 42e <exit>
000001d9 <stosb>:
"cc");
}
static inline void
stosb(void *addr, int data, int cnt)
{
1d9: 55 push %ebp
1da: 89 e5 mov %esp,%ebp
1dc: 57 push %edi
1dd: 53 push %ebx
asm volatile("cld; rep stosb" :
1de: 8b 4d 08 mov 0x8(%ebp),%ecx
1e1: 8b 55 10 mov 0x10(%ebp),%edx
1e4: 8b 45 0c mov 0xc(%ebp),%eax
1e7: 89 cb mov %ecx,%ebx
1e9: 89 df mov %ebx,%edi
1eb: 89 d1 mov %edx,%ecx
1ed: fc cld
1ee: f3 aa rep stos %al,%es:(%edi)
1f0: 89 ca mov %ecx,%edx
1f2: 89 fb mov %edi,%ebx
1f4: 89 5d 08 mov %ebx,0x8(%ebp)
1f7: 89 55 10 mov %edx,0x10(%ebp)
"=D" (addr), "=c" (cnt) :
"0" (addr), "1" (cnt), "a" (data) :
"memory", "cc");
}
1fa: 5b pop %ebx
1fb: 5f pop %edi
1fc: 5d pop %ebp
1fd: c3 ret
000001fe <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, char *t)
{
1fe: 55 push %ebp
1ff: 89 e5 mov %esp,%ebp
201: 83 ec 10 sub $0x10,%esp
char *os;
os = s;
204: 8b 45 08 mov 0x8(%ebp),%eax
207: 89 45 fc mov %eax,-0x4(%ebp)
while((*s++ = *t++) != 0)
20a: 90 nop
20b: 8b 45 08 mov 0x8(%ebp),%eax
20e: 8d 50 01 lea 0x1(%eax),%edx
211: 89 55 08 mov %edx,0x8(%ebp)
214: 8b 55 0c mov 0xc(%ebp),%edx
217: 8d 4a 01 lea 0x1(%edx),%ecx
21a: 89 4d 0c mov %ecx,0xc(%ebp)
21d: 0f b6 12 movzbl (%edx),%edx
220: 88 10 mov %dl,(%eax)
222: 0f b6 00 movzbl (%eax),%eax
225: 84 c0 test %al,%al
227: 75 e2 jne 20b <strcpy+0xd>
;
return os;
229: 8b 45 fc mov -0x4(%ebp),%eax
}
22c: c9 leave
22d: c3 ret
0000022e <strcmp>:
int
strcmp(const char *p, const char *q)
{
22e: 55 push %ebp
22f: 89 e5 mov %esp,%ebp
while(*p && *p == *q)
231: eb 08 jmp 23b <strcmp+0xd>
p++, q++;
233: 83 45 08 01 addl $0x1,0x8(%ebp)
237: 83 45 0c 01 addl $0x1,0xc(%ebp)
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
23b: 8b 45 08 mov 0x8(%ebp),%eax
23e: 0f b6 00 movzbl (%eax),%eax
241: 84 c0 test %al,%al
243: 74 10 je 255 <strcmp+0x27>
245: 8b 45 08 mov 0x8(%ebp),%eax
248: 0f b6 10 movzbl (%eax),%edx
24b: 8b 45 0c mov 0xc(%ebp),%eax
24e: 0f b6 00 movzbl (%eax),%eax
251: 38 c2 cmp %al,%dl
253: 74 de je 233 <strcmp+0x5>
p++, q++;
return (uchar)*p - (uchar)*q;
255: 8b 45 08 mov 0x8(%ebp),%eax
258: 0f b6 00 movzbl (%eax),%eax
25b: 0f b6 d0 movzbl %al,%edx
25e: 8b 45 0c mov 0xc(%ebp),%eax
261: 0f b6 00 movzbl (%eax),%eax
264: 0f b6 c0 movzbl %al,%eax
267: 29 c2 sub %eax,%edx
269: 89 d0 mov %edx,%eax
}
26b: 5d pop %ebp
26c: c3 ret
0000026d <strlen>:
uint
strlen(char *s)
{
26d: 55 push %ebp
26e: 89 e5 mov %esp,%ebp
270: 83 ec 10 sub $0x10,%esp
int n;
for(n = 0; s[n]; n++)
273: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp)
27a: eb 04 jmp 280 <strlen+0x13>
27c: 83 45 fc 01 addl $0x1,-0x4(%ebp)
280: 8b 55 fc mov -0x4(%ebp),%edx
283: 8b 45 08 mov 0x8(%ebp),%eax
286: 01 d0 add %edx,%eax
288: 0f b6 00 movzbl (%eax),%eax
28b: 84 c0 test %al,%al
28d: 75 ed jne 27c <strlen+0xf>
;
return n;
28f: 8b 45 fc mov -0x4(%ebp),%eax
}
292: c9 leave
293: c3 ret
00000294 <memset>:
void*
memset(void *dst, int c, uint n)
{
294: 55 push %ebp
295: 89 e5 mov %esp,%ebp
stosb(dst, c, n);
297: 8b 45 10 mov 0x10(%ebp),%eax
29a: 50 push %eax
29b: ff 75 0c pushl 0xc(%ebp)
29e: ff 75 08 pushl 0x8(%ebp)
2a1: e8 33 ff ff ff call 1d9 <stosb>
2a6: 83 c4 0c add $0xc,%esp
return dst;
2a9: 8b 45 08 mov 0x8(%ebp),%eax
}
2ac: c9 leave
2ad: c3 ret
000002ae <strchr>:
char*
strchr(const char *s, char c)
{
2ae: 55 push %ebp
2af: 89 e5 mov %esp,%ebp
2b1: 83 ec 04 sub $0x4,%esp
2b4: 8b 45 0c mov 0xc(%ebp),%eax
2b7: 88 45 fc mov %al,-0x4(%ebp)
for(; *s; s++)
2ba: eb 14 jmp 2d0 <strchr+0x22>
if(*s == c)
2bc: 8b 45 08 mov 0x8(%ebp),%eax
2bf: 0f b6 00 movzbl (%eax),%eax
2c2: 3a 45 fc cmp -0x4(%ebp),%al
2c5: 75 05 jne 2cc <strchr+0x1e>
return (char*)s;
2c7: 8b 45 08 mov 0x8(%ebp),%eax
2ca: eb 13 jmp 2df <strchr+0x31>
}
char*
strchr(const char *s, char c)
{
for(; *s; s++)
2cc: 83 45 08 01 addl $0x1,0x8(%ebp)
2d0: 8b 45 08 mov 0x8(%ebp),%eax
2d3: 0f b6 00 movzbl (%eax),%eax
2d6: 84 c0 test %al,%al
2d8: 75 e2 jne 2bc <strchr+0xe>
if(*s == c)
return (char*)s;
return 0;
2da: b8 00 00 00 00 mov $0x0,%eax
}
2df: c9 leave
2e0: c3 ret
000002e1 <gets>:
char*
gets(char *buf, int max)
{
2e1: 55 push %ebp
2e2: 89 e5 mov %esp,%ebp
2e4: 83 ec 18 sub $0x18,%esp
int i, cc;
char c;
for(i=0; i+1 < max; ){
2e7: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
2ee: eb 44 jmp 334 <gets+0x53>
cc = read(0, &c, 1);
2f0: 83 ec 04 sub $0x4,%esp
2f3: 6a 01 push $0x1
2f5: 8d 45 ef lea -0x11(%ebp),%eax
2f8: 50 push %eax
2f9: 6a 00 push $0x0
2fb: e8 46 01 00 00 call 446 <read>
300: 83 c4 10 add $0x10,%esp
303: 89 45 f0 mov %eax,-0x10(%ebp)
if(cc < 1)
306: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
30a: 7f 02 jg 30e <gets+0x2d>
break;
30c: eb 31 jmp 33f <gets+0x5e>
buf[i++] = c;
30e: 8b 45 f4 mov -0xc(%ebp),%eax
311: 8d 50 01 lea 0x1(%eax),%edx
314: 89 55 f4 mov %edx,-0xc(%ebp)
317: 89 c2 mov %eax,%edx
319: 8b 45 08 mov 0x8(%ebp),%eax
31c: 01 c2 add %eax,%edx
31e: 0f b6 45 ef movzbl -0x11(%ebp),%eax
322: 88 02 mov %al,(%edx)
if(c == '\n' || c == '\r')
324: 0f b6 45 ef movzbl -0x11(%ebp),%eax
328: 3c 0a cmp $0xa,%al
32a: 74 13 je 33f <gets+0x5e>
32c: 0f b6 45 ef movzbl -0x11(%ebp),%eax
330: 3c 0d cmp $0xd,%al
332: 74 0b je 33f <gets+0x5e>
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
334: 8b 45 f4 mov -0xc(%ebp),%eax
337: 83 c0 01 add $0x1,%eax
33a: 3b 45 0c cmp 0xc(%ebp),%eax
33d: 7c b1 jl 2f0 <gets+0xf>
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
33f: 8b 55 f4 mov -0xc(%ebp),%edx
342: 8b 45 08 mov 0x8(%ebp),%eax
345: 01 d0 add %edx,%eax
347: c6 00 00 movb $0x0,(%eax)
return buf;
34a: 8b 45 08 mov 0x8(%ebp),%eax
}
34d: c9 leave
34e: c3 ret
0000034f <stat>:
int
stat(char *n, struct stat *st)
{
34f: 55 push %ebp
350: 89 e5 mov %esp,%ebp
352: 83 ec 18 sub $0x18,%esp
int fd;
int r;
fd = open(n, O_RDONLY);
355: 83 ec 08 sub $0x8,%esp
358: 6a 00 push $0x0
35a: ff 75 08 pushl 0x8(%ebp)
35d: e8 0c 01 00 00 call 46e <open>
362: 83 c4 10 add $0x10,%esp
365: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0)
368: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
36c: 79 07 jns 375 <stat+0x26>
return -1;
36e: b8 ff ff ff ff mov $0xffffffff,%eax
373: eb 25 jmp 39a <stat+0x4b>
r = fstat(fd, st);
375: 83 ec 08 sub $0x8,%esp
378: ff 75 0c pushl 0xc(%ebp)
37b: ff 75 f4 pushl -0xc(%ebp)
37e: e8 03 01 00 00 call 486 <fstat>
383: 83 c4 10 add $0x10,%esp
386: 89 45 f0 mov %eax,-0x10(%ebp)
close(fd);
389: 83 ec 0c sub $0xc,%esp
38c: ff 75 f4 pushl -0xc(%ebp)
38f: e8 c2 00 00 00 call 456 <close>
394: 83 c4 10 add $0x10,%esp
return r;
397: 8b 45 f0 mov -0x10(%ebp),%eax
}
39a: c9 leave
39b: c3 ret
0000039c <atoi>:
int
atoi(const char *s)
{
39c: 55 push %ebp
39d: 89 e5 mov %esp,%ebp
39f: 83 ec 10 sub $0x10,%esp
int n;
n = 0;
3a2: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp)
while('0' <= *s && *s <= '9')
3a9: eb 25 jmp 3d0 <atoi+0x34>
n = n*10 + *s++ - '0';
3ab: 8b 55 fc mov -0x4(%ebp),%edx
3ae: 89 d0 mov %edx,%eax
3b0: c1 e0 02 shl $0x2,%eax
3b3: 01 d0 add %edx,%eax
3b5: 01 c0 add %eax,%eax
3b7: 89 c1 mov %eax,%ecx
3b9: 8b 45 08 mov 0x8(%ebp),%eax
3bc: 8d 50 01 lea 0x1(%eax),%edx
3bf: 89 55 08 mov %edx,0x8(%ebp)
3c2: 0f b6 00 movzbl (%eax),%eax
3c5: 0f be c0 movsbl %al,%eax
3c8: 01 c8 add %ecx,%eax
3ca: 83 e8 30 sub $0x30,%eax
3cd: 89 45 fc mov %eax,-0x4(%ebp)
atoi(const char *s)
{
int n;
n = 0;
while('0' <= *s && *s <= '9')
3d0: 8b 45 08 mov 0x8(%ebp),%eax
3d3: 0f b6 00 movzbl (%eax),%eax
3d6: 3c 2f cmp $0x2f,%al
3d8: 7e 0a jle 3e4 <atoi+0x48>
3da: 8b 45 08 mov 0x8(%ebp),%eax
3dd: 0f b6 00 movzbl (%eax),%eax
3e0: 3c 39 cmp $0x39,%al
3e2: 7e c7 jle 3ab <atoi+0xf>
n = n*10 + *s++ - '0';
return n;
3e4: 8b 45 fc mov -0x4(%ebp),%eax
}
3e7: c9 leave
3e8: c3 ret
000003e9 <memmove>:
void*
memmove(void *vdst, void *vsrc, int n)
{
3e9: 55 push %ebp
3ea: 89 e5 mov %esp,%ebp
3ec: 83 ec 10 sub $0x10,%esp
char *dst, *src;
dst = vdst;
3ef: 8b 45 08 mov 0x8(%ebp),%eax
3f2: 89 45 fc mov %eax,-0x4(%ebp)
src = vsrc;
3f5: 8b 45 0c mov 0xc(%ebp),%eax
3f8: 89 45 f8 mov %eax,-0x8(%ebp)
while(n-- > 0)
3fb: eb 17 jmp 414 <memmove+0x2b>
*dst++ = *src++;
3fd: 8b 45 fc mov -0x4(%ebp),%eax
400: 8d 50 01 lea 0x1(%eax),%edx
403: 89 55 fc mov %edx,-0x4(%ebp)
406: 8b 55 f8 mov -0x8(%ebp),%edx
409: 8d 4a 01 lea 0x1(%edx),%ecx
40c: 89 4d f8 mov %ecx,-0x8(%ebp)
40f: 0f b6 12 movzbl (%edx),%edx
412: 88 10 mov %dl,(%eax)
{
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
414: 8b 45 10 mov 0x10(%ebp),%eax
417: 8d 50 ff lea -0x1(%eax),%edx
41a: 89 55 10 mov %edx,0x10(%ebp)
41d: 85 c0 test %eax,%eax
41f: 7f dc jg 3fd <memmove+0x14>
*dst++ = *src++;
return vdst;
421: 8b 45 08 mov 0x8(%ebp),%eax
}
424: c9 leave
425: c3 ret
00000426 <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
426: b8 01 00 00 00 mov $0x1,%eax
42b: cd 40 int $0x40
42d: c3 ret
0000042e <exit>:
SYSCALL(exit)
42e: b8 02 00 00 00 mov $0x2,%eax
433: cd 40 int $0x40
435: c3 ret
00000436 <wait>:
SYSCALL(wait)
436: b8 03 00 00 00 mov $0x3,%eax
43b: cd 40 int $0x40
43d: c3 ret
0000043e <pipe>:
SYSCALL(pipe)
43e: b8 04 00 00 00 mov $0x4,%eax
443: cd 40 int $0x40
445: c3 ret
00000446 <read>:
SYSCALL(read)
446: b8 05 00 00 00 mov $0x5,%eax
44b: cd 40 int $0x40
44d: c3 ret
0000044e <write>:
SYSCALL(write)
44e: b8 10 00 00 00 mov $0x10,%eax
453: cd 40 int $0x40
455: c3 ret
00000456 <close>:
SYSCALL(close)
456: b8 15 00 00 00 mov $0x15,%eax
45b: cd 40 int $0x40
45d: c3 ret
0000045e <kill>:
SYSCALL(kill)
45e: b8 06 00 00 00 mov $0x6,%eax
463: cd 40 int $0x40
465: c3 ret
00000466 <exec>:
SYSCALL(exec)
466: b8 07 00 00 00 mov $0x7,%eax
46b: cd 40 int $0x40
46d: c3 ret
0000046e <open>:
SYSCALL(open)
46e: b8 0f 00 00 00 mov $0xf,%eax
473: cd 40 int $0x40
475: c3 ret
00000476 <mknod>:
SYSCALL(mknod)
476: b8 11 00 00 00 mov $0x11,%eax
47b: cd 40 int $0x40
47d: c3 ret
0000047e <unlink>:
SYSCALL(unlink)
47e: b8 12 00 00 00 mov $0x12,%eax
483: cd 40 int $0x40
485: c3 ret
00000486 <fstat>:
SYSCALL(fstat)
486: b8 08 00 00 00 mov $0x8,%eax
48b: cd 40 int $0x40
48d: c3 ret
0000048e <link>:
SYSCALL(link)
48e: b8 13 00 00 00 mov $0x13,%eax
493: cd 40 int $0x40
495: c3 ret
00000496 <mkdir>:
SYSCALL(mkdir)
496: b8 14 00 00 00 mov $0x14,%eax
49b: cd 40 int $0x40
49d: c3 ret
0000049e <chdir>:
SYSCALL(chdir)
49e: b8 09 00 00 00 mov $0x9,%eax
4a3: cd 40 int $0x40
4a5: c3 ret
000004a6 <dup>:
SYSCALL(dup)
4a6: b8 0a 00 00 00 mov $0xa,%eax
4ab: cd 40 int $0x40
4ad: c3 ret
000004ae <getpid>:
SYSCALL(getpid)
4ae: b8 0b 00 00 00 mov $0xb,%eax
4b3: cd 40 int $0x40
4b5: c3 ret
000004b6 <sbrk>:
SYSCALL(sbrk)
4b6: b8 0c 00 00 00 mov $0xc,%eax
4bb: cd 40 int $0x40
4bd: c3 ret
000004be <sleep>:
SYSCALL(sleep)
4be: b8 0d 00 00 00 mov $0xd,%eax
4c3: cd 40 int $0x40
4c5: c3 ret
000004c6 <uptime>:
SYSCALL(uptime)
4c6: b8 0e 00 00 00 mov $0xe,%eax
4cb: cd 40 int $0x40
4cd: c3 ret
000004ce <trace>:
SYSCALL(trace)
4ce: b8 16 00 00 00 mov $0x16,%eax
4d3: cd 40 int $0x40
4d5: c3 ret
000004d6 <putc>:
#include "stat.h"
#include "user.h"
static void
putc(int fd, char c)
{
4d6: 55 push %ebp
4d7: 89 e5 mov %esp,%ebp
4d9: 83 ec 18 sub $0x18,%esp
4dc: 8b 45 0c mov 0xc(%ebp),%eax
4df: 88 45 f4 mov %al,-0xc(%ebp)
write(fd, &c, 1);
4e2: 83 ec 04 sub $0x4,%esp
4e5: 6a 01 push $0x1
4e7: 8d 45 f4 lea -0xc(%ebp),%eax
4ea: 50 push %eax
4eb: ff 75 08 pushl 0x8(%ebp)
4ee: e8 5b ff ff ff call 44e <write>
4f3: 83 c4 10 add $0x10,%esp
}
4f6: c9 leave
4f7: c3 ret
000004f8 <printint>:
static void
printint(int fd, int xx, int base, int sgn)
{
4f8: 55 push %ebp
4f9: 89 e5 mov %esp,%ebp
4fb: 53 push %ebx
4fc: 83 ec 24 sub $0x24,%esp
static char digits[] = "0123456789ABCDEF";
char buf[16];
int i, neg;
uint x;
neg = 0;
4ff: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
if(sgn && xx < 0){
506: 83 7d 14 00 cmpl $0x0,0x14(%ebp)
50a: 74 17 je 523 <printint+0x2b>
50c: 83 7d 0c 00 cmpl $0x0,0xc(%ebp)
510: 79 11 jns 523 <printint+0x2b>
neg = 1;
512: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp)
x = -xx;
519: 8b 45 0c mov 0xc(%ebp),%eax
51c: f7 d8 neg %eax
51e: 89 45 ec mov %eax,-0x14(%ebp)
521: eb 06 jmp 529 <printint+0x31>
} else {
x = xx;
523: 8b 45 0c mov 0xc(%ebp),%eax
526: 89 45 ec mov %eax,-0x14(%ebp)
}
i = 0;
529: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
do{
buf[i++] = digits[x % base];
530: 8b 4d f4 mov -0xc(%ebp),%ecx
533: 8d 41 01 lea 0x1(%ecx),%eax
536: 89 45 f4 mov %eax,-0xc(%ebp)
539: 8b 5d 10 mov 0x10(%ebp),%ebx
53c: 8b 45 ec mov -0x14(%ebp),%eax
53f: ba 00 00 00 00 mov $0x0,%edx
544: f7 f3 div %ebx
546: 89 d0 mov %edx,%eax
548: 0f b6 80 24 0c 00 00 movzbl 0xc24(%eax),%eax
54f: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1)
}while((x /= base) != 0);
553: 8b 5d 10 mov 0x10(%ebp),%ebx
556: 8b 45 ec mov -0x14(%ebp),%eax
559: ba 00 00 00 00 mov $0x0,%edx
55e: f7 f3 div %ebx
560: 89 45 ec mov %eax,-0x14(%ebp)
563: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
567: 75 c7 jne 530 <printint+0x38>
if(neg)
569: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
56d: 74 0e je 57d <printint+0x85>
buf[i++] = '-';
56f: 8b 45 f4 mov -0xc(%ebp),%eax
572: 8d 50 01 lea 0x1(%eax),%edx
575: 89 55 f4 mov %edx,-0xc(%ebp)
578: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1)
while(--i >= 0)
57d: eb 1d jmp 59c <printint+0xa4>
putc(fd, buf[i]);
57f: 8d 55 dc lea -0x24(%ebp),%edx
582: 8b 45 f4 mov -0xc(%ebp),%eax
585: 01 d0 add %edx,%eax
587: 0f b6 00 movzbl (%eax),%eax
58a: 0f be c0 movsbl %al,%eax
58d: 83 ec 08 sub $0x8,%esp
590: 50 push %eax
591: ff 75 08 pushl 0x8(%ebp)
594: e8 3d ff ff ff call 4d6 <putc>
599: 83 c4 10 add $0x10,%esp
buf[i++] = digits[x % base];
}while((x /= base) != 0);
if(neg)
buf[i++] = '-';
while(--i >= 0)
59c: 83 6d f4 01 subl $0x1,-0xc(%ebp)
5a0: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
5a4: 79 d9 jns 57f <printint+0x87>
putc(fd, buf[i]);
}
5a6: 8b 5d fc mov -0x4(%ebp),%ebx
5a9: c9 leave
5aa: c3 ret
000005ab <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
5ab: 55 push %ebp
5ac: 89 e5 mov %esp,%ebp
5ae: 83 ec 28 sub $0x28,%esp
char *s;
int c, i, state;
uint *ap;
state = 0;
5b1: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
ap = (uint*)(void*)&fmt + 1;
5b8: 8d 45 0c lea 0xc(%ebp),%eax
5bb: 83 c0 04 add $0x4,%eax
5be: 89 45 e8 mov %eax,-0x18(%ebp)
for(i = 0; fmt[i]; i++){
5c1: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
5c8: e9 59 01 00 00 jmp 726 <printf+0x17b>
c = fmt[i] & 0xff;
5cd: 8b 55 0c mov 0xc(%ebp),%edx
5d0: 8b 45 f0 mov -0x10(%ebp),%eax
5d3: 01 d0 add %edx,%eax
5d5: 0f b6 00 movzbl (%eax),%eax
5d8: 0f be c0 movsbl %al,%eax
5db: 25 ff 00 00 00 and $0xff,%eax
5e0: 89 45 e4 mov %eax,-0x1c(%ebp)
if(state == 0){
5e3: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
5e7: 75 2c jne 615 <printf+0x6a>
if(c == '%'){
5e9: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp)
5ed: 75 0c jne 5fb <printf+0x50>
state = '%';
5ef: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp)
5f6: e9 27 01 00 00 jmp 722 <printf+0x177>
} else {
putc(fd, c);
5fb: 8b 45 e4 mov -0x1c(%ebp),%eax
5fe: 0f be c0 movsbl %al,%eax
601: 83 ec 08 sub $0x8,%esp
604: 50 push %eax
605: ff 75 08 pushl 0x8(%ebp)
608: e8 c9 fe ff ff call 4d6 <putc>
60d: 83 c4 10 add $0x10,%esp
610: e9 0d 01 00 00 jmp 722 <printf+0x177>
}
} else if(state == '%'){
615: 83 7d ec 25 cmpl $0x25,-0x14(%ebp)
619: 0f 85 03 01 00 00 jne 722 <printf+0x177>
if(c == 'd'){
61f: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp)
623: 75 1e jne 643 <printf+0x98>
printint(fd, *ap, 10, 1);
625: 8b 45 e8 mov -0x18(%ebp),%eax
628: 8b 00 mov (%eax),%eax
62a: 6a 01 push $0x1
62c: 6a 0a push $0xa
62e: 50 push %eax
62f: ff 75 08 pushl 0x8(%ebp)
632: e8 c1 fe ff ff call 4f8 <printint>
637: 83 c4 10 add $0x10,%esp
ap++;
63a: 83 45 e8 04 addl $0x4,-0x18(%ebp)
63e: e9 d8 00 00 00 jmp 71b <printf+0x170>
} else if(c == 'x' || c == 'p'){
643: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp)
647: 74 06 je 64f <printf+0xa4>
649: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp)
64d: 75 1e jne 66d <printf+0xc2>
printint(fd, *ap, 16, 0);
64f: 8b 45 e8 mov -0x18(%ebp),%eax
652: 8b 00 mov (%eax),%eax
654: 6a 00 push $0x0
656: 6a 10 push $0x10
658: 50 push %eax
659: ff 75 08 pushl 0x8(%ebp)
65c: e8 97 fe ff ff call 4f8 <printint>
661: 83 c4 10 add $0x10,%esp
ap++;
664: 83 45 e8 04 addl $0x4,-0x18(%ebp)
668: e9 ae 00 00 00 jmp 71b <printf+0x170>
} else if(c == 's'){
66d: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp)
671: 75 43 jne 6b6 <printf+0x10b>
s = (char*)*ap;
673: 8b 45 e8 mov -0x18(%ebp),%eax
676: 8b 00 mov (%eax),%eax
678: 89 45 f4 mov %eax,-0xc(%ebp)
ap++;
67b: 83 45 e8 04 addl $0x4,-0x18(%ebp)
if(s == 0)
67f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
683: 75 07 jne 68c <printf+0xe1>
s = "(null)";
685: c7 45 f4 d2 09 00 00 movl $0x9d2,-0xc(%ebp)
while(*s != 0){
68c: eb 1c jmp 6aa <printf+0xff>
putc(fd, *s);
68e: 8b 45 f4 mov -0xc(%ebp),%eax
691: 0f b6 00 movzbl (%eax),%eax
694: 0f be c0 movsbl %al,%eax
697: 83 ec 08 sub $0x8,%esp
69a: 50 push %eax
69b: ff 75 08 pushl 0x8(%ebp)
69e: e8 33 fe ff ff call 4d6 <putc>
6a3: 83 c4 10 add $0x10,%esp
s++;
6a6: 83 45 f4 01 addl $0x1,-0xc(%ebp)
} else if(c == 's'){
s = (char*)*ap;
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
6aa: 8b 45 f4 mov -0xc(%ebp),%eax
6ad: 0f b6 00 movzbl (%eax),%eax
6b0: 84 c0 test %al,%al
6b2: 75 da jne 68e <printf+0xe3>
6b4: eb 65 jmp 71b <printf+0x170>
putc(fd, *s);
s++;
}
} else if(c == 'c'){
6b6: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp)
6ba: 75 1d jne 6d9 <printf+0x12e>
putc(fd, *ap);
6bc: 8b 45 e8 mov -0x18(%ebp),%eax
6bf: 8b 00 mov (%eax),%eax
6c1: 0f be c0 movsbl %al,%eax
6c4: 83 ec 08 sub $0x8,%esp
6c7: 50 push %eax
6c8: ff 75 08 pushl 0x8(%ebp)
6cb: e8 06 fe ff ff call 4d6 <putc>
6d0: 83 c4 10 add $0x10,%esp
ap++;
6d3: 83 45 e8 04 addl $0x4,-0x18(%ebp)
6d7: eb 42 jmp 71b <printf+0x170>
} else if(c == '%'){
6d9: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp)
6dd: 75 17 jne 6f6 <printf+0x14b>
putc(fd, c);
6df: 8b 45 e4 mov -0x1c(%ebp),%eax
6e2: 0f be c0 movsbl %al,%eax
6e5: 83 ec 08 sub $0x8,%esp
6e8: 50 push %eax
6e9: ff 75 08 pushl 0x8(%ebp)
6ec: e8 e5 fd ff ff call 4d6 <putc>
6f1: 83 c4 10 add $0x10,%esp
6f4: eb 25 jmp 71b <printf+0x170>
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
6f6: 83 ec 08 sub $0x8,%esp
6f9: 6a 25 push $0x25
6fb: ff 75 08 pushl 0x8(%ebp)
6fe: e8 d3 fd ff ff call 4d6 <putc>
703: 83 c4 10 add $0x10,%esp
putc(fd, c);
706: 8b 45 e4 mov -0x1c(%ebp),%eax
709: 0f be c0 movsbl %al,%eax
70c: 83 ec 08 sub $0x8,%esp
70f: 50 push %eax
710: ff 75 08 pushl 0x8(%ebp)
713: e8 be fd ff ff call 4d6 <putc>
718: 83 c4 10 add $0x10,%esp
}
state = 0;
71b: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
722: 83 45 f0 01 addl $0x1,-0x10(%ebp)
726: 8b 55 0c mov 0xc(%ebp),%edx
729: 8b 45 f0 mov -0x10(%ebp),%eax
72c: 01 d0 add %edx,%eax
72e: 0f b6 00 movzbl (%eax),%eax
731: 84 c0 test %al,%al
733: 0f 85 94 fe ff ff jne 5cd <printf+0x22>
putc(fd, c);
}
state = 0;
}
}
}
739: c9 leave
73a: c3 ret
0000073b <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
73b: 55 push %ebp
73c: 89 e5 mov %esp,%ebp
73e: 83 ec 10 sub $0x10,%esp
Header *bp, *p;
bp = (Header*)ap - 1;
741: 8b 45 08 mov 0x8(%ebp),%eax
744: 83 e8 08 sub $0x8,%eax
747: 89 45 f8 mov %eax,-0x8(%ebp)
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
74a: a1 40 0c 00 00 mov 0xc40,%eax
74f: 89 45 fc mov %eax,-0x4(%ebp)
752: eb 24 jmp 778 <free+0x3d>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
754: 8b 45 fc mov -0x4(%ebp),%eax
757: 8b 00 mov (%eax),%eax
759: 3b 45 fc cmp -0x4(%ebp),%eax
75c: 77 12 ja 770 <free+0x35>
75e: 8b 45 f8 mov -0x8(%ebp),%eax
761: 3b 45 fc cmp -0x4(%ebp),%eax
764: 77 24 ja 78a <free+0x4f>
766: 8b 45 fc mov -0x4(%ebp),%eax
769: 8b 00 mov (%eax),%eax
76b: 3b 45 f8 cmp -0x8(%ebp),%eax
76e: 77 1a ja 78a <free+0x4f>
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
770: 8b 45 fc mov -0x4(%ebp),%eax
773: 8b 00 mov (%eax),%eax
775: 89 45 fc mov %eax,-0x4(%ebp)
778: 8b 45 f8 mov -0x8(%ebp),%eax
77b: 3b 45 fc cmp -0x4(%ebp),%eax
77e: 76 d4 jbe 754 <free+0x19>
780: 8b 45 fc mov -0x4(%ebp),%eax
783: 8b 00 mov (%eax),%eax
785: 3b 45 f8 cmp -0x8(%ebp),%eax
788: 76 ca jbe 754 <free+0x19>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
78a: 8b 45 f8 mov -0x8(%ebp),%eax
78d: 8b 40 04 mov 0x4(%eax),%eax
790: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx
797: 8b 45 f8 mov -0x8(%ebp),%eax
79a: 01 c2 add %eax,%edx
79c: 8b 45 fc mov -0x4(%ebp),%eax
79f: 8b 00 mov (%eax),%eax
7a1: 39 c2 cmp %eax,%edx
7a3: 75 24 jne 7c9 <free+0x8e>
bp->s.size += p->s.ptr->s.size;
7a5: 8b 45 f8 mov -0x8(%ebp),%eax
7a8: 8b 50 04 mov 0x4(%eax),%edx
7ab: 8b 45 fc mov -0x4(%ebp),%eax
7ae: 8b 00 mov (%eax),%eax
7b0: 8b 40 04 mov 0x4(%eax),%eax
7b3: 01 c2 add %eax,%edx
7b5: 8b 45 f8 mov -0x8(%ebp),%eax
7b8: 89 50 04 mov %edx,0x4(%eax)
bp->s.ptr = p->s.ptr->s.ptr;
7bb: 8b 45 fc mov -0x4(%ebp),%eax
7be: 8b 00 mov (%eax),%eax
7c0: 8b 10 mov (%eax),%edx
7c2: 8b 45 f8 mov -0x8(%ebp),%eax
7c5: 89 10 mov %edx,(%eax)
7c7: eb 0a jmp 7d3 <free+0x98>
} else
bp->s.ptr = p->s.ptr;
7c9: 8b 45 fc mov -0x4(%ebp),%eax
7cc: 8b 10 mov (%eax),%edx
7ce: 8b 45 f8 mov -0x8(%ebp),%eax
7d1: 89 10 mov %edx,(%eax)
if(p + p->s.size == bp){
7d3: 8b 45 fc mov -0x4(%ebp),%eax
7d6: 8b 40 04 mov 0x4(%eax),%eax
7d9: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx
7e0: 8b 45 fc mov -0x4(%ebp),%eax
7e3: 01 d0 add %edx,%eax
7e5: 3b 45 f8 cmp -0x8(%ebp),%eax
7e8: 75 20 jne 80a <free+0xcf>
p->s.size += bp->s.size;
7ea: 8b 45 fc mov -0x4(%ebp),%eax
7ed: 8b 50 04 mov 0x4(%eax),%edx
7f0: 8b 45 f8 mov -0x8(%ebp),%eax
7f3: 8b 40 04 mov 0x4(%eax),%eax
7f6: 01 c2 add %eax,%edx
7f8: 8b 45 fc mov -0x4(%ebp),%eax
7fb: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
7fe: 8b 45 f8 mov -0x8(%ebp),%eax
801: 8b 10 mov (%eax),%edx
803: 8b 45 fc mov -0x4(%ebp),%eax
806: 89 10 mov %edx,(%eax)
808: eb 08 jmp 812 <free+0xd7>
} else
p->s.ptr = bp;
80a: 8b 45 fc mov -0x4(%ebp),%eax
80d: 8b 55 f8 mov -0x8(%ebp),%edx
810: 89 10 mov %edx,(%eax)
freep = p;
812: 8b 45 fc mov -0x4(%ebp),%eax
815: a3 40 0c 00 00 mov %eax,0xc40
}
81a: c9 leave
81b: c3 ret
0000081c <morecore>:
static Header*
morecore(uint nu)
{
81c: 55 push %ebp
81d: 89 e5 mov %esp,%ebp
81f: 83 ec 18 sub $0x18,%esp
char *p;
Header *hp;
if(nu < 4096)
822: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp)
829: 77 07 ja 832 <morecore+0x16>
nu = 4096;
82b: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp)
p = sbrk(nu * sizeof(Header));
832: 8b 45 08 mov 0x8(%ebp),%eax
835: c1 e0 03 shl $0x3,%eax
838: 83 ec 0c sub $0xc,%esp
83b: 50 push %eax
83c: e8 75 fc ff ff call 4b6 <sbrk>
841: 83 c4 10 add $0x10,%esp
844: 89 45 f4 mov %eax,-0xc(%ebp)
if(p == (char*)-1)
847: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp)
84b: 75 07 jne 854 <morecore+0x38>
return 0;
84d: b8 00 00 00 00 mov $0x0,%eax
852: eb 26 jmp 87a <morecore+0x5e>
hp = (Header*)p;
854: 8b 45 f4 mov -0xc(%ebp),%eax
857: 89 45 f0 mov %eax,-0x10(%ebp)
hp->s.size = nu;
85a: 8b 45 f0 mov -0x10(%ebp),%eax
85d: 8b 55 08 mov 0x8(%ebp),%edx
860: 89 50 04 mov %edx,0x4(%eax)
free((void*)(hp + 1));
863: 8b 45 f0 mov -0x10(%ebp),%eax
866: 83 c0 08 add $0x8,%eax
869: 83 ec 0c sub $0xc,%esp
86c: 50 push %eax
86d: e8 c9 fe ff ff call 73b <free>
872: 83 c4 10 add $0x10,%esp
return freep;
875: a1 40 0c 00 00 mov 0xc40,%eax
}
87a: c9 leave
87b: c3 ret
0000087c <malloc>:
void*
malloc(uint nbytes)
{
87c: 55 push %ebp
87d: 89 e5 mov %esp,%ebp
87f: 83 ec 18 sub $0x18,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
882: 8b 45 08 mov 0x8(%ebp),%eax
885: 83 c0 07 add $0x7,%eax
888: c1 e8 03 shr $0x3,%eax
88b: 83 c0 01 add $0x1,%eax
88e: 89 45 ec mov %eax,-0x14(%ebp)
if((prevp = freep) == 0){
891: a1 40 0c 00 00 mov 0xc40,%eax
896: 89 45 f0 mov %eax,-0x10(%ebp)
899: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
89d: 75 23 jne 8c2 <malloc+0x46>
base.s.ptr = freep = prevp = &base;
89f: c7 45 f0 38 0c 00 00 movl $0xc38,-0x10(%ebp)
8a6: 8b 45 f0 mov -0x10(%ebp),%eax
8a9: a3 40 0c 00 00 mov %eax,0xc40
8ae: a1 40 0c 00 00 mov 0xc40,%eax
8b3: a3 38 0c 00 00 mov %eax,0xc38
base.s.size = 0;
8b8: c7 05 3c 0c 00 00 00 movl $0x0,0xc3c
8bf: 00 00 00
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
8c2: 8b 45 f0 mov -0x10(%ebp),%eax
8c5: 8b 00 mov (%eax),%eax
8c7: 89 45 f4 mov %eax,-0xc(%ebp)
if(p->s.size >= nunits){
8ca: 8b 45 f4 mov -0xc(%ebp),%eax
8cd: 8b 40 04 mov 0x4(%eax),%eax
8d0: 3b 45 ec cmp -0x14(%ebp),%eax
8d3: 72 4d jb 922 <malloc+0xa6>
if(p->s.size == nunits)
8d5: 8b 45 f4 mov -0xc(%ebp),%eax
8d8: 8b 40 04 mov 0x4(%eax),%eax
8db: 3b 45 ec cmp -0x14(%ebp),%eax
8de: 75 0c jne 8ec <malloc+0x70>
prevp->s.ptr = p->s.ptr;
8e0: 8b 45 f4 mov -0xc(%ebp),%eax
8e3: 8b 10 mov (%eax),%edx
8e5: 8b 45 f0 mov -0x10(%ebp),%eax
8e8: 89 10 mov %edx,(%eax)
8ea: eb 26 jmp 912 <malloc+0x96>
else {
p->s.size -= nunits;
8ec: 8b 45 f4 mov -0xc(%ebp),%eax
8ef: 8b 40 04 mov 0x4(%eax),%eax
8f2: 2b 45 ec sub -0x14(%ebp),%eax
8f5: 89 c2 mov %eax,%edx
8f7: 8b 45 f4 mov -0xc(%ebp),%eax
8fa: 89 50 04 mov %edx,0x4(%eax)
p += p->s.size;
8fd: 8b 45 f4 mov -0xc(%ebp),%eax
900: 8b 40 04 mov 0x4(%eax),%eax
903: c1 e0 03 shl $0x3,%eax
906: 01 45 f4 add %eax,-0xc(%ebp)
p->s.size = nunits;
909: 8b 45 f4 mov -0xc(%ebp),%eax
90c: 8b 55 ec mov -0x14(%ebp),%edx
90f: 89 50 04 mov %edx,0x4(%eax)
}
freep = prevp;
912: 8b 45 f0 mov -0x10(%ebp),%eax
915: a3 40 0c 00 00 mov %eax,0xc40
return (void*)(p + 1);
91a: 8b 45 f4 mov -0xc(%ebp),%eax
91d: 83 c0 08 add $0x8,%eax
920: eb 3b jmp 95d <malloc+0xe1>
}
if(p == freep)
922: a1 40 0c 00 00 mov 0xc40,%eax
927: 39 45 f4 cmp %eax,-0xc(%ebp)
92a: 75 1e jne 94a <malloc+0xce>
if((p = morecore(nunits)) == 0)
92c: 83 ec 0c sub $0xc,%esp
92f: ff 75 ec pushl -0x14(%ebp)
932: e8 e5 fe ff ff call 81c <morecore>
937: 83 c4 10 add $0x10,%esp
93a: 89 45 f4 mov %eax,-0xc(%ebp)
93d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
941: 75 07 jne 94a <malloc+0xce>
return 0;
943: b8 00 00 00 00 mov $0x0,%eax
948: eb 13 jmp 95d <malloc+0xe1>
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
94a: 8b 45 f4 mov -0xc(%ebp),%eax
94d: 89 45 f0 mov %eax,-0x10(%ebp)
950: 8b 45 f4 mov -0xc(%ebp),%eax
953: 8b 00 mov (%eax),%eax
955: 89 45 f4 mov %eax,-0xc(%ebp)
return (void*)(p + 1);
}
if(p == freep)
if((p = morecore(nunits)) == 0)
return 0;
}
958: e9 6d ff ff ff jmp 8ca <malloc+0x4e>
}
95d: c9 leave
95e: c3 ret
|
; A288732: a(n) = a(n-1) + 2*a(n-4) - 2*a(n-5) for n >= 5, where a(0) = 2, a(1) = 4, a(2) = 6, a(3) = 8, a(4) = 10.
; 2,4,6,8,10,14,18,22,26,34,42,50,58,74,90,106,122,154,186,218,250,314,378,442,506,634,762,890,1018,1274,1530,1786,2042,2554,3066,3578,4090,5114,6138,7162,8186,10234,12282,14330,16378,20474,24570,28666,32762,40954,49146,57338,65530,81914,98298,114682,131066,163834,196602,229370,262138,327674,393210,458746,524282,655354,786426,917498,1048570,1310714,1572858,1835002,2097146,2621434,3145722,3670010,4194298,5242874,6291450,7340026,8388602,10485754,12582906,14680058,16777210,20971514,25165818,29360122
lpb $0
mov $2,$0
lpb $2
sub $0,2
add $1,1
mod $2,4
lpe
sub $0,$2
add $1,$2
mul $1,2
lpe
add $1,2
mov $0,$1
|
; Identical to lesson 13's boot sector, but the %included files have new paths
[org 0x7c00]
KERNEL_OFFSET equ 0x1000 ; The same one we used when linking the kernel
mov [BOOT_DRIVE], dl ; Remember that the BIOS sets us the boot drive in 'dl' on boot
mov bp, 0x9000
mov sp, bp
mov bx, MSG_REAL_MODE
call print
call print_nl
call load_kernel ; read the kernel from disk
call switch_to_pm ; disable interrupts, load GDT, etc. Finally jumps to 'BEGIN_PM'
jmp $ ; Never executed
%include "boot/print.asm"
%include "boot/print_hex.asm"
%include "boot/disk.asm"
%include "boot/gdt.asm"
%include "boot/32bit_print.asm"
%include "boot/switch_pm.asm"
[bits 16]
load_kernel:
mov bx, MSG_LOAD_KERNEL
call print
call print_nl
mov bx, KERNEL_OFFSET ; Read from disk and store in 0x1000
mov dh, 16 ; Our future kernel will be larger, make this big
mov dl, [BOOT_DRIVE]
call disk_load
ret
[bits 32]
BEGIN_PM:
mov ebx, MSG_PROT_MODE
call print_string_pm
call KERNEL_OFFSET ; Give control to the kernel
jmp $ ; Stay here when the kernel returns control to us (if ever)
BOOT_DRIVE db 0 ; It is a good idea to store it in memory because 'dl' may get overwritten
MSG_REAL_MODE db "Started in 16-bit Real Mode", 0
MSG_PROT_MODE db "Landed in 32-bit Protected Mode", 0
MSG_LOAD_KERNEL db "Loading kernel into memory", 0
; padding
times 510 - ($-$$) db 0
dw 0xaa55
|
; A004455: Nimsum n + 14.
; 14,15,12,13,10,11,8,9,6,7,4,5,2,3,0,1,30,31,28,29,26,27,24,25,22,23,20,21,18,19,16,17,46,47,44,45,42,43,40,41,38,39,36,37,34,35,32,33,62,63,60,61,58,59,56,57,54,55,52,53,50,51,48,49,78,79,76,77,74,75,72,73,70,71,68,69,66,67,64,65,94,95,92,93,90,91,88,89,86,87,84,85,82,83,80,81,110,111,108,109,106,107,104,105,102,103,100,101,98,99,96,97,126,127,124,125,122,123,120,121,118,119,116,117,114,115,112,113,142,143,140,141,138,139,136,137,134,135,132,133,130,131,128,129,158,159,156,157,154,155,152,153,150,151,148,149,146,147,144,145,174,175,172,173,170,171,168,169,166,167,164,165,162,163,160,161,190,191,188,189,186,187,184,185,182,183,180,181,178,179,176,177,206,207,204,205,202,203,200,201,198,199,196,197,194,195,192,193,222,223,220,221,218,219,216,217,214,215,212,213,210,211,208,209,238,239,236,237,234,235,232,233,230,231,228,229,226,227,224,225,254,255,252,253,250,251,248,249,246,247
mov $3,$0
div $0,2
mod $0,8
mov $1,1
mov $2,$0
add $2,$0
mul $2,2
sub $1,$2
add $1,13
add $1,$3
|
-- 7 Billion Humans (2053) --
-- 58: Good Neighbors --
-- Author: soerface
-- Size: 46
-- Speed: 36
a:
b:
mem1 = nearest datacube
step mem1
c:
if c == nothing:
jump a
endif
if c != 8:
step nw,w,sw,n,s,ne,e,se
jump c
endif
pickup c
mem1 = nearest wall
step mem1
d:
if e == wall or
w == wall:
if c == datacube:
step n
jump d
endif
endif
e:
if n == wall or
s == wall:
if c == datacube:
step w
jump e
endif
endif
drop
if n == wall:
step s
step s
step s
step s
step s
endif
if e == wall:
step w
step w
step w
step w
step w
step w
endif
if s == wall:
step n
step n
step n
step n
step n
endif
if w == wall:
step e
step e
step e
step e
step e
step e
endif
jump b
|
//*****************************************************************************
// Copyright 2017-2021 Intel Corporation
//
// 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.
//*****************************************************************************
#pragma once
#include <memory>
#include "ngraph/node.hpp"
#include "onnx_import/core/node.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace op
{
namespace set_1
{
OutputVector add(const Node& node);
} // namespace set_1
namespace set_7
{
OutputVector add(const Node& node);
} // namespace set_7
} // namespace op
} // namespace onnx_import
} // namespace ngraph
|
;
; Tape save routine
;
; djm 16/10/2001
;
; int __CALLEE__ tape_save_block_callee(void *addr, size_t len, unsigned char type)
PUBLIC tape_save_block_callee
PUBLIC _tape_save_block_callee
PUBLIC ASMDISP_TAPE_SAVE_BLOCK_CALLEE
IF FORts2068
EXTERN call_extrom
ELSE
EXTERN call_rom3
ENDIF
.tape_save_block_callee
._tape_save_block_callee
pop hl
pop bc
ld a,c
pop de
pop ix
push hl
; enter : ix = addr
; de = len
; a = type
.asmentry
IF FORts2068
ld hl,$68
call call_extrom
ld hl,0
ret
ELSE
ld hl,(23613)
push hl
ld hl,saveblock1
push hl
ld (23613),sp
call call_rom3
defw 1218 ;call ROM3 routine
;pop hl ;successfull dump the random value
ld hl,0
.saveblock2
pop de
pop de
ld (23613),de ;get back original 23613
ret
.saveblock1
ld hl,-1 ;error
jr saveblock2
ENDIF
DEFC ASMDISP_TAPE_SAVE_BLOCK_CALLEE = # asmentry - tape_save_block_callee
|
addi r3 r0 -1
andi r4 r3 65
tty r4
halt
# prints A |
;this kernel just renders some fancy shapes on the screen
org 0x8000
bits 16
mov ah, 0 ;set display mode
mov al, 13h ;13h = 320x200
int 0x10
mov al, 2 ;COLOR
mov cx, 30 ;X-POS
mov dx, 20 ;Y-POS
mov si, 32 ;X-SIZE
mov di, 32
call drawCircle
mov al, 4
mov cx, 128
mov dx, 30
call drawBox
jmp $
;------------------------------------------------------
;cx = xpos , dx = ypos, si = x-length, di = y-length, al = color
drawBox:
push si ;save x-length
.for_x:
push di ;save y-length
.for_y:
pusha
;mov al, 1 ;color value
mov bh, 0 ;page number
add cx, si ;cx = x-coordinate
add dx, di ;dx = y-coordinate
mov ah, 0xC ;write pixel at coordinate
int 0x10 ;might "destroy" ax, si and di on some systems
popa
sub di, 1 ;decrease di by one and set flags
jnz .for_y ;repeat for y-length
pop di ;restore di
sub si, 1 ;decrease si by one and set flags
jnz .for_x ;repeat for x-length
pop si ;restore si
ret
;------------------------------------------------------
;------------------------------------------------------
;cx = xpos , dx = ypos, si = radius, al = color
drawCircle:
pusha ;save all registers
mov di, si
add di, si ; di = si * 2
mov bp, si ;bp is just another general purpose register for us
add si, si ; si = si * 2
.for_x:
push di ;save y-length
.for_y:
pusha
add cx, si ;cx = x-coordinate
add dx, di ;dx = y-coordinate
; (x-r)^2 + (y-r)^2 = (distance of x,y from middle of circle with radius r) ^ 2
; (x-r)^2 + (y-r)^2 <= r^2 , as long as radius squared is bigger than distance squared ,point is within the circle
; (si-bp)^2 + (di-bp)^2 <= bp^2
sub si, bp ;di = y - r
sub di, bp ;di = x - r
imul si, si ;si = x^2
imul di, di ;di = y^2
add si, di ;add (x-r)^2 and (y-r)^2
imul bp, bp ;signed multiplication, r * r = r^2
cmp si, bp ;if r^2 >= distance^2: point is within circle
jg .skip ;if greater: point is not within circle
;mov al, 1 ;color value
mov bh, 0 ;page number
mov ah, 0xC ;write pixel at coordinate
int 0x10 ;might "destroy" ax, si and di on some systems
.skip:
popa
sub di, 1 ;decrease di by one and set flags
jnz .for_y ;repeat for y-length
pop di ;restore di
sub si, 1 ;decrease si by one and set flags
jnz .for_x ;repeat for x-length
popa ;restore all registers
ret
;------------------------------------------------------
%assign usedMemory ($-$$)
%assign usableMemory (512*16)
%warning [usedMemory/usableMemory] Bytes used
times (512*16)-($-$$) db 0 ;kernel must have size multiple of 512 so let's pad it to the correct size |
#include <stdio.h>
#include <math.h>
int fac(int x)
{
int i, fac=1;
for(i=1; i<=x; i++)
fac=fac*1;
return fac
}
int main ()
{
float x, Q, sum=0;
int i,j, limit;
limit = 10;
printf("Enter the value of xof sinx series: ");
scanf("%f,&x);
Q=x*(3.1415/180);
for(i=1, j=1; i<=limit; i++,j=j+2)
{
if(i%2!=0)
{
sum=sum+pow(x,j)/fac(j);
}
else
sum=sum-pow(x,y)/fac(j);
}
printf("Sin(%0.1f): %f", Q,sum);
return 0;
}
|
; A040763: Continued fraction for sqrt(792).
; 28,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56,7,56
pow $0,4
mov $1,$0
trn $0,4
sub $0,4
gcd $1,$0
mul $1,7
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <cstring>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/vr/test/xr_browser_test.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "url/gurl.h"
namespace vr {
constexpr base::TimeDelta XrBrowserTestBase::kPollCheckIntervalShort;
constexpr base::TimeDelta XrBrowserTestBase::kPollCheckIntervalLong;
constexpr base::TimeDelta XrBrowserTestBase::kPollTimeoutShort;
constexpr base::TimeDelta XrBrowserTestBase::kPollTimeoutMedium;
constexpr base::TimeDelta XrBrowserTestBase::kPollTimeoutLong;
constexpr char XrBrowserTestBase::kOpenXrConfigPathEnvVar[];
constexpr char XrBrowserTestBase::kOpenXrConfigPathVal[];
constexpr char XrBrowserTestBase::kTestFileDir[];
constexpr char XrBrowserTestBase::kSwitchIgnoreRuntimeRequirements[];
const std::vector<std::string> XrBrowserTestBase::kRequiredTestSwitches{
"enable-gpu", "enable-pixel-output-in-tests",
"run-through-xr-wrapper-script"};
const std::vector<std::pair<std::string, std::string>>
XrBrowserTestBase::kRequiredTestSwitchesWithValues{
std::pair<std::string, std::string>("test-launcher-jobs", "1")};
XrBrowserTestBase::XrBrowserTestBase() : env_(base::Environment::Create()) {
enable_features_.push_back(features::kLogJsConsoleMessages);
}
XrBrowserTestBase::~XrBrowserTestBase() = default;
base::FilePath::StringType UTF8ToWideIfNecessary(std::string input) {
#ifdef OS_WIN
return base::UTF8ToWide(input);
#else
return input;
#endif // OS_WIN
}
std::string WideToUTF8IfNecessary(base::FilePath::StringType input) {
#ifdef OS_WIN
return base::WideToUTF8(input);
#else
return input;
#endif // OS_Win
}
// Returns an std::string consisting of the given path relative to the test
// executable's path, e.g. if the executable is in out/Debug and the given path
// is "test", the returned string should be out/Debug/test.
std::string MakeExecutableRelative(const char* path) {
base::FilePath executable_path;
EXPECT_TRUE(
base::PathService::Get(base::BasePathKey::FILE_EXE, &executable_path));
executable_path = executable_path.DirName();
// We need an std::string that is an absolute file path, which requires
// platform-specific logic since Windows uses std::wstring instead of
// std::string for FilePaths, but SetVar only accepts std::string.
return WideToUTF8IfNecessary(
base::MakeAbsoluteFilePath(
executable_path.Append(base::FilePath(UTF8ToWideIfNecessary(path))))
.value());
}
void XrBrowserTestBase::SetUp() {
// Check whether the required flags were passed to the test - without these,
// we can fail in ways that are non-obvious, so fail more explicitly here if
// they aren't present.
auto* cmd_line = base::CommandLine::ForCurrentProcess();
for (auto req_switch : kRequiredTestSwitches) {
ASSERT_TRUE(cmd_line->HasSwitch(req_switch))
<< "Missing switch " << req_switch << " required to run tests properly";
}
for (auto req_switch_pair : kRequiredTestSwitchesWithValues) {
ASSERT_TRUE(cmd_line->HasSwitch(req_switch_pair.first))
<< "Missing switch " << req_switch_pair.first
<< " required to run tests properly";
ASSERT_TRUE(cmd_line->GetSwitchValueASCII(req_switch_pair.first) ==
req_switch_pair.second)
<< "Have required switch " << req_switch_pair.first
<< ", but not required value " << req_switch_pair.second;
}
// Get the set of runtime requirements to ignore.
if (cmd_line->HasSwitch(kSwitchIgnoreRuntimeRequirements)) {
auto reqs = cmd_line->GetSwitchValueASCII(kSwitchIgnoreRuntimeRequirements);
if (reqs != "") {
for (auto req : base::SplitString(
reqs, ",", base::WhitespaceHandling::TRIM_WHITESPACE,
base::SplitResult::SPLIT_WANT_NONEMPTY)) {
ignored_requirements_.insert(req);
}
}
}
// Check whether we meet all runtime requirements for this test.
XR_CONDITIONAL_SKIP_PRETEST(runtime_requirements_, ignored_requirements_,
&test_skipped_at_startup_)
// Set the environment variable to use the mock OpenXR client.
// If the kOpenXrConfigPathEnvVar environment variable is set, the OpenXR
// loader will look for the OpenXR runtime specified in that json file. The
// json file contains the path to the runtime, relative to the json file
// itself. Otherwise, the OpenXR loader loads the active OpenXR runtime
// installed on the system, which is specified by a registry key.
ASSERT_TRUE(env_->SetVar(kOpenXrConfigPathEnvVar,
MakeExecutableRelative(kOpenXrConfigPathVal)))
<< "Failed to set OpenXR JSON location environment variable";
// Set any command line flags that subclasses have set, e.g. enabling features
// or specific runtimes.
for (const auto& switch_string : append_switches_) {
cmd_line->AppendSwitch(switch_string);
}
for (const auto& blink_feature : enable_blink_features_) {
cmd_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, blink_feature);
}
scoped_feature_list_.InitWithFeatures(enable_features_, disable_features_);
InProcessBrowserTest::SetUp();
}
void XrBrowserTestBase::TearDown() {
if (test_skipped_at_startup_) {
// Since we didn't complete startup, no need to do teardown, either. Doing
// so can result in hitting a DCHECK.
return;
}
InProcessBrowserTest::TearDown();
}
XrBrowserTestBase::RuntimeType XrBrowserTestBase::GetRuntimeType() const {
return XrBrowserTestBase::RuntimeType::RUNTIME_NONE;
}
GURL XrBrowserTestBase::GetUrlForFile(const std::string& test_name) {
// GetURL requires that the path start with /.
return GetEmbeddedServer()->GetURL(std::string("/") + kTestFileDir +
test_name + ".html");
}
net::EmbeddedTestServer* XrBrowserTestBase::GetEmbeddedServer() {
if (server_ == nullptr) {
server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::Type::TYPE_HTTPS);
// We need to serve from the root in order for the inclusion of the
// test harness from //third_party to work.
server_->ServeFilesFromSourceDirectory(".");
EXPECT_TRUE(server_->Start()) << "Failed to start embedded test server";
}
return server_.get();
}
content::WebContents* XrBrowserTestBase::GetCurrentWebContents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
void XrBrowserTestBase::LoadFileAndAwaitInitialization(
const std::string& test_name) {
GURL url = GetUrlForFile(test_name);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
ASSERT_TRUE(PollJavaScriptBoolean("isInitializationComplete()",
kPollTimeoutMedium,
GetCurrentWebContents()))
<< "Timed out waiting for JavaScript test initialization.";
#if defined(OS_WIN)
// Now that the browser is opened and has focus, keep track of this window so
// that we can restore the proper focus after entering each session. This is
// required for tests that create multiple sessions to work properly.
hwnd_ = GetForegroundWindow();
#endif
}
void XrBrowserTestBase::RunJavaScriptOrFail(
const std::string& js_expression,
content::WebContents* web_contents) {
if (javascript_failed_) {
LogJavaScriptFailure();
return;
}
ASSERT_TRUE(content::ExecuteScript(web_contents, js_expression))
<< "Failed to run given JavaScript: " << js_expression;
}
bool XrBrowserTestBase::RunJavaScriptAndExtractBoolOrFail(
const std::string& js_expression,
content::WebContents* web_contents) {
if (javascript_failed_) {
LogJavaScriptFailure();
return false;
}
bool result;
DLOG(INFO) << "Run JavaScript: " << js_expression;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
web_contents,
"window.domAutomationController.send(" + js_expression + ")", &result))
<< "Failed to run given JavaScript for bool: " << js_expression;
return result;
}
std::string XrBrowserTestBase::RunJavaScriptAndExtractStringOrFail(
const std::string& js_expression,
content::WebContents* web_contents) {
if (javascript_failed_) {
LogJavaScriptFailure();
return "";
}
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
web_contents,
"window.domAutomationController.send(" + js_expression + ")", &result))
<< "Failed to run given JavaScript for string: " << js_expression;
return result;
}
bool XrBrowserTestBase::PollJavaScriptBoolean(
const std::string& bool_expression,
const base::TimeDelta& timeout,
content::WebContents* web_contents) {
bool result = false;
base::RunLoop wait_loop(base::RunLoop::Type::kNestableTasksAllowed);
// Lambda used because otherwise BindRepeating gets confused about which
// version of RunJavaScriptAndExtractBoolOrFail to use.
BlockOnCondition(base::BindRepeating(
[](XrBrowserTestBase* base, std::string expression,
content::WebContents* contents) {
return base->RunJavaScriptAndExtractBoolOrFail(
expression, contents);
},
this, bool_expression, web_contents),
&result, &wait_loop, base::Time::Now(), timeout);
wait_loop.Run();
return result;
}
void XrBrowserTestBase::PollJavaScriptBooleanOrFail(
const std::string& bool_expression,
const base::TimeDelta& timeout,
content::WebContents* web_contents) {
ASSERT_TRUE(PollJavaScriptBoolean(bool_expression, timeout, web_contents))
<< "Timed out polling JavaScript boolean expression: " << bool_expression;
}
void XrBrowserTestBase::BlockOnCondition(
base::RepeatingCallback<bool()> condition,
bool* result,
base::RunLoop* wait_loop,
const base::Time& start_time,
const base::TimeDelta& timeout,
const base::TimeDelta& period) {
if (!*result) {
*result = condition.Run();
}
if (*result) {
if (wait_loop->running()) {
wait_loop->Quit();
return;
}
// In the case where the condition is met fast enough that the given
// RunLoop hasn't started yet, spin until it's available.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&XrBrowserTestBase::BlockOnCondition,
base::Unretained(this), std::move(condition),
base::Unretained(result), base::Unretained(wait_loop),
start_time, timeout, period));
return;
}
if (base::Time::Now() - start_time > timeout &&
!base::debug::BeingDebugged()) {
wait_loop->Quit();
return;
}
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&XrBrowserTestBase::BlockOnCondition,
base::Unretained(this), std::move(condition),
base::Unretained(result), base::Unretained(wait_loop),
start_time, timeout, period),
period);
}
void XrBrowserTestBase::WaitOnJavaScriptStep(
content::WebContents* web_contents) {
// Make sure we aren't trying to wait on a JavaScript test step without the
// code to do so.
bool code_available = RunJavaScriptAndExtractBoolOrFail(
"typeof javascriptDone !== 'undefined'", web_contents);
ASSERT_TRUE(code_available) << "Attempted to wait on a JavaScript test step "
<< "without the code to do so. You either forgot "
<< "to import webxr_e2e.js or "
<< "are incorrectly using a C++ function.";
// Actually wait for the step to finish.
bool success =
PollJavaScriptBoolean("javascriptDone", kPollTimeoutLong, web_contents);
// Check what state we're in to make sure javascriptDone wasn't called
// because the test failed.
XrBrowserTestBase::TestStatus test_status = CheckTestStatus(web_contents);
if (!success || test_status == XrBrowserTestBase::TestStatus::STATUS_FAILED) {
// Failure states: Either polling failed or polling succeeded, but because
// the test failed.
std::string reason;
if (!success) {
reason = "Timed out waiting for JavaScript step to finish.";
} else {
reason =
"JavaScript testharness reported failure while waiting for "
"JavaScript step to finish";
}
std::string result_string =
RunJavaScriptAndExtractStringOrFail("resultString", web_contents);
if (result_string.empty()) {
reason +=
" Did not obtain specific failure reason from JavaScript "
"testharness.";
} else {
reason +=
" JavaScript testharness reported failure reason: " + result_string;
}
// Store that we've failed waiting for a JavaScript step so we can abort
// further attempts to run JavaScript, which has the potential to do weird
// things and produce non-useful output due to JavaScript code continuing
// to run when it's in a known bad state.
// This is a workaround for the fact that FAIL() and other gtest macros that
// cause test failures only abort the current function. Thus, a failure here
// will show up as a test failure, but there's nothing that actually stops
// the test from continuing to run since FAIL() is not being called in the
// main test body.
javascript_failed_ = true;
// Newlines to help the failure reason stick out.
LOG(ERROR) << "\n\n\nvvvvvvvvvvvvvvvvv Useful Stack vvvvvvvvvvvvvvvvv\n\n";
FAIL() << reason;
}
// Reset the synchronization boolean.
RunJavaScriptOrFail("javascriptDone = false", web_contents);
}
void XrBrowserTestBase::ExecuteStepAndWait(const std::string& step_function,
content::WebContents* web_contents) {
RunJavaScriptOrFail(step_function, web_contents);
WaitOnJavaScriptStep(web_contents);
}
XrBrowserTestBase::TestStatus XrBrowserTestBase::CheckTestStatus(
content::WebContents* web_contents) {
std::string result_string =
RunJavaScriptAndExtractStringOrFail("resultString", web_contents);
bool test_passed =
RunJavaScriptAndExtractBoolOrFail("testPassed", web_contents);
if (test_passed) {
return XrBrowserTestBase::TestStatus::STATUS_PASSED;
} else if (!test_passed && result_string.empty()) {
return XrBrowserTestBase::TestStatus::STATUS_RUNNING;
}
// !test_passed && result_string != ""
return XrBrowserTestBase::TestStatus::STATUS_FAILED;
}
void XrBrowserTestBase::EndTest(content::WebContents* web_contents) {
switch (CheckTestStatus(web_contents)) {
case XrBrowserTestBase::TestStatus::STATUS_PASSED:
break;
case XrBrowserTestBase::TestStatus::STATUS_FAILED:
FAIL() << "JavaScript testharness failed with reason: "
<< RunJavaScriptAndExtractStringOrFail("resultString",
web_contents);
case XrBrowserTestBase::TestStatus::STATUS_RUNNING:
FAIL() << "Attempted to end test in C++ without finishing in JavaScript.";
default:
FAIL() << "Received unknown test status.";
}
}
void XrBrowserTestBase::AssertNoJavaScriptErrors(
content::WebContents* web_contents) {
if (CheckTestStatus(web_contents) ==
XrBrowserTestBase::TestStatus::STATUS_FAILED) {
FAIL() << "JavaScript testharness failed with reason: "
<< RunJavaScriptAndExtractStringOrFail("resultString", web_contents);
}
}
void XrBrowserTestBase::RunJavaScriptOrFail(const std::string& js_expression) {
RunJavaScriptOrFail(js_expression, GetCurrentWebContents());
}
bool XrBrowserTestBase::RunJavaScriptAndExtractBoolOrFail(
const std::string& js_expression) {
return RunJavaScriptAndExtractBoolOrFail(js_expression,
GetCurrentWebContents());
}
std::string XrBrowserTestBase::RunJavaScriptAndExtractStringOrFail(
const std::string& js_expression) {
return RunJavaScriptAndExtractStringOrFail(js_expression,
GetCurrentWebContents());
}
bool XrBrowserTestBase::PollJavaScriptBoolean(
const std::string& bool_expression,
const base::TimeDelta& timeout) {
return PollJavaScriptBoolean(bool_expression, timeout,
GetCurrentWebContents());
}
void XrBrowserTestBase::PollJavaScriptBooleanOrFail(
const std::string& bool_expression,
const base::TimeDelta& timeout) {
PollJavaScriptBooleanOrFail(bool_expression, timeout,
GetCurrentWebContents());
}
void XrBrowserTestBase::WaitOnJavaScriptStep() {
WaitOnJavaScriptStep(GetCurrentWebContents());
}
void XrBrowserTestBase::ExecuteStepAndWait(const std::string& step_function) {
ExecuteStepAndWait(step_function, GetCurrentWebContents());
}
void XrBrowserTestBase::EndTest() {
EndTest(GetCurrentWebContents());
}
void XrBrowserTestBase::AssertNoJavaScriptErrors() {
AssertNoJavaScriptErrors(GetCurrentWebContents());
}
void XrBrowserTestBase::LogJavaScriptFailure() {
LOG(ERROR) << "HEY! LISTEN! Not running requested JavaScript due to previous "
"failure. Failures below this are likely garbage. Look for the "
"useful stack above.";
}
} // namespace vr
|
; A106043: First digit other than 9 in the fractional part of the decimal expansion of (1/1000^n)^(1/1000^n).
; 0,3,8,7,7,6,5,5,4,3,3,2,1,1,0,8,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4
mul $0,62298
lpb $0
mov $2,$0
div $0,10
mod $2,10
add $0,$2
lpe
mov $0,$2
|
; A198075: Round((n+1/n)^10).
; Submitted by Christian Krause
; 1024,9537,169351,1922602,14455511,79525194,345716130,1253815679,3941971041,11046221254,28162516240,66354069277,146236468527,304356025989,602797997503,1143224193789,2086847748927,3682210047877,6303034667439,10498899284253,17061992477838,27113811835076,42216316373726,64512773675388,96904343881502,143269322488388,208732925307726,299996545666076,425736549529838,597083902389252,828197246045438,1136943467546876,1545701330044926,2082305369910788,2781149009707502,3684467696168988,4843824849832526
add $0,1
pow $0,2
mov $1,$0
pow $0,4
mul $0,$1
add $1,1
pow $1,10
mul $1,2
add $1,$0
mul $0,2
div $1,$0
mov $0,$1
|
; A004183: Omit 8's from n.
; 0,1,2,3,4,5,6,7,0,9,10,11,12,13,14,15,16,17,1,19,20,21,22,23,24,25,26,27,2,29,30,31,32,33,34,35,36,37,3,39,40,41,42,43,44,45,46,47,4,49,50,51,52,53,54,55,56,57,5,59,60,61,62,63,64,65,66,67,6,69,70,71
mov $1,$0
add $1,1
mov $2,1
lpb $2,1
add $2,$1
mov $1,3
add $1,$0
mod $2,10
add $3,11
lpe
lpb $3,1
div $1,3
div $3,7
lpe
sub $1,1
|
; A081589: Third row of Pascal-(1,5,1) array A081580.
; 1,13,61,145,265,421,613,841,1105,1405,1741,2113,2521,2965,3445,3961,4513,5101,5725,6385,7081,7813,8581,9385,10225,11101,12013,12961,13945,14965,16021,17113,18241,19405,20605,21841,23113,24421,25765,27145,28561,30013,31501,33025,34585,36181,37813,39481,41185,42925,44701,46513,48361,50245,52165,54121,56113,58141,60205,62305,64441,66613,68821,71065,73345,75661,78013,80401,82825,85285,87781,90313,92881,95485,98125,100801,103513,106261,109045,111865,114721,117613,120541,123505,126505,129541,132613,135721,138865,142045,145261,148513,151801,155125,158485,161881,165313,168781,172285,175825,179401,183013,186661,190345,194065,197821,201613,205441,209305,213205,217141,221113,225121,229165,233245,237361,241513,245701,249925,254185,258481,262813,267181,271585,276025,280501,285013,289561,294145,298765,303421,308113,312841,317605,322405,327241,332113,337021,341965,346945,351961,357013,362101,367225,372385,377581,382813,388081,393385,398725,404101,409513,414961,420445,425965,431521,437113,442741,448405,454105,459841,465613,471421,477265,483145,489061,495013,501001,507025,513085,519181,525313,531481,537685,543925,550201,556513,562861,569245,575665,582121,588613,595141,601705,608305,614941,621613,628321,635065,641845,648661,655513,662401,669325,676285,683281,690313,697381,704485,711625,718801,726013,733261,740545,747865,755221,762613,770041,777505,785005,792541,800113,807721,815365,823045,830761,838513,846301,854125,861985,869881,877813,885781,893785,901825,909901,918013,926161,934345,942565,950821,959113,967441,975805,984205,992641,1001113,1009621,1018165,1026745,1035361,1044013,1052701,1061425,1070185,1078981,1087813,1096681,1105585,1114525
mul $0,3
bin $0,2
mov $1,$0
div $1,3
mul $1,12
add $1,1
|
/**
* Copyright (C) 2018 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located 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.
*/
#include "Section.h"
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "XclBinUtilities.h"
namespace XUtil = XclBinUtilities;
// Static Variables Initialization
std::map<enum axlf_section_kind, std::string> Section::m_mapIdToName;
std::map<std::string, enum axlf_section_kind> Section::m_mapNameToId;
std::map<enum axlf_section_kind, Section::Section_factory> Section::m_mapIdToCtor;
std::map<std::string, enum axlf_section_kind> Section::m_mapJSONNameToKind;
std::map<enum axlf_section_kind, bool> Section::m_mapIdToSubSectionSupport;
Section::Section()
: m_eKind(BITSTREAM)
, m_sKindName("")
, m_pBuffer(nullptr)
, m_bufferSize(0)
, m_name("") {
// Empty
}
Section::~Section() {
purgeBuffers();
}
void
Section::purgeBuffers()
{
if (m_pBuffer != nullptr) {
delete m_pBuffer;
m_pBuffer = nullptr;
}
m_bufferSize = 0;
}
void
Section::setName(const std::string &_sSectionName)
{
m_name = _sSectionName;
}
void
Section::getKinds(std::vector< std::string > & kinds) {
for (auto & item : m_mapNameToId) {
kinds.push_back(item.first);
}
}
void
Section::registerSectionCtor(enum axlf_section_kind _eKind,
const std::string& _sKindStr,
const std::string& _sHeaderJSONName,
bool _bSupportsSubSections,
Section_factory _Section_factory) {
// Some error checking
if (_sKindStr.empty()) {
std::string errMsg = XUtil::format("ERROR: Kind (%d) pretty print name is missing.", _eKind);
throw std::runtime_error(errMsg);
}
if (m_mapIdToName.find(_eKind) != m_mapIdToName.end()) {
std::string errMsg = XUtil::format("ERROR: Attempting to register (%d : %s). Constructor enum of kind (%d) already registered.",
(unsigned int)_eKind, _sKindStr.c_str(), (unsigned int)_eKind);
throw std::runtime_error(errMsg);
}
if (m_mapNameToId.find(_sKindStr) != m_mapNameToId.end()) {
std::string errMsg = XUtil::format("ERROR: Attempting to register: (%d : %s). Constructor name '%s' already registered to eKind (%d).",
(unsigned int)_eKind, _sKindStr.c_str(),
_sKindStr.c_str(), (unsigned int)m_mapNameToId[_sKindStr]);
throw std::runtime_error(errMsg);
}
if (!_sHeaderJSONName.empty()) {
if (m_mapJSONNameToKind.find(_sHeaderJSONName) != m_mapJSONNameToKind.end()) {
std::string errMsg = XUtil::format("ERROR: Attempting to register: (%d : %s). JSON mapping name '%s' already registered to eKind (%d).",
(unsigned int)_eKind, _sKindStr.c_str(),
_sHeaderJSONName.c_str(), (unsigned int)m_mapJSONNameToKind[_sHeaderJSONName]);
throw std::runtime_error(errMsg);
}
m_mapJSONNameToKind[_sHeaderJSONName] = _eKind;
}
// At this point we know we are good, lets initialize the arrays
m_mapIdToName[_eKind] = _sKindStr;
m_mapNameToId[_sKindStr] = _eKind;
m_mapIdToCtor[_eKind] = _Section_factory;
m_mapIdToSubSectionSupport[_eKind] = _bSupportsSubSections;
}
bool
Section::translateSectionKindStrToKind(const std::string &_sKindStr, enum axlf_section_kind &_eKind)
{
if (m_mapNameToId.find(_sKindStr) == m_mapNameToId.end()) {
return false;
}
_eKind = m_mapNameToId[_sKindStr];
return true;
}
bool
Section::supportsSubSections(enum axlf_section_kind &_eKind)
{
if (m_mapIdToSubSectionSupport.find(_eKind) == m_mapIdToSubSectionSupport.end()) {
return false;
}
return m_mapIdToSubSectionSupport[_eKind];
}
enum Section::FormatType
Section::getFormatType(const std::string _sFormatType)
{
std::string sFormatType = _sFormatType;
boost::to_upper(sFormatType);
if (sFormatType == "") { return FT_UNDEFINED; }
if (sFormatType == "RAW") { return FT_RAW; }
if (sFormatType == "JSON") { return FT_JSON; }
if (sFormatType == "HTML") { return FT_HTML; }
if (sFormatType == "TXT") { return FT_TXT; }
return FT_UNKNOWN;
}
bool
Section::getKindOfJSON(const std::string &_sJSONStr, enum axlf_section_kind &_eKind) {
if (_sJSONStr.empty() ||
(m_mapJSONNameToKind.find(_sJSONStr) == m_mapJSONNameToKind.end()) ) {
return false;
}
_eKind = m_mapJSONNameToKind[_sJSONStr];
return true;
}
Section*
Section::createSectionObjectOfKind(enum axlf_section_kind _eKind) {
Section* pSection = nullptr;
if (m_mapIdToCtor.find(_eKind) == m_mapIdToCtor.end()) {
std::string errMsg = XUtil::format("ERROR: Constructor for enum (%d) is missing.", (unsigned int)_eKind);
throw std::runtime_error(errMsg);
}
pSection = m_mapIdToCtor[_eKind]();
pSection->m_eKind = _eKind;
pSection->m_sKindName = m_mapIdToName[_eKind];
XUtil::TRACE(XUtil::format("Created segment: %s (%d)",
pSection->getSectionKindAsString().c_str(),
(unsigned int)pSection->getSectionKind()));
return pSection;
}
enum axlf_section_kind
Section::getSectionKind() const {
return m_eKind;
}
const std::string&
Section::getSectionKindAsString() const {
return m_sKindName;
}
std::string
Section::getName() const {
return m_name;
}
unsigned int
Section::getSize() const {
return m_bufferSize;
}
void
Section::initXclBinSectionHeader(axlf_section_header& _sectionHeader) {
_sectionHeader.m_sectionKind = m_eKind;
_sectionHeader.m_sectionSize = m_bufferSize;
XUtil::safeStringCopy((char*)&_sectionHeader.m_sectionName, m_name, sizeof(axlf_section_header::m_sectionName));
}
void
Section::writeXclBinSectionBuffer(std::fstream& _ostream) const
{
if ((m_pBuffer == nullptr) ||
(m_bufferSize == 0)) {
return;
}
_ostream.write(m_pBuffer, m_bufferSize);
}
void
Section::readXclBinBinary(std::fstream& _istream, const axlf_section_header& _sectionHeader) {
// Some error checking
if ((enum axlf_section_kind)_sectionHeader.m_sectionKind != getSectionKind()) {
std::string errMsg = XUtil::format("ERROR: Unexpected section kind. Expected: %d, Read: %d", getSectionKind(), _sectionHeader.m_sectionKind);
throw std::runtime_error(errMsg);
}
if (m_pBuffer != nullptr) {
std::string errMsg = "ERROR: Binary buffer already exists.";
throw std::runtime_error(errMsg);
}
m_name = (char*)&_sectionHeader.m_sectionName;
m_bufferSize = _sectionHeader.m_sectionSize;
m_pBuffer = new char[m_bufferSize];
_istream.seekg(_sectionHeader.m_sectionOffset);
_istream.read(m_pBuffer, m_bufferSize);
if (_istream.gcount() != m_bufferSize) {
std::string errMsg = "ERROR: Input stream for the binary buffer is smaller then the expected size.";
throw std::runtime_error(errMsg);
}
XUtil::TRACE(XUtil::format("Section: %s (%d)", getSectionKindAsString().c_str(), (unsigned int)getSectionKind()));
XUtil::TRACE(XUtil::format(" m_name: %s", m_name.c_str()));
XUtil::TRACE(XUtil::format(" m_size: %ld", m_bufferSize));
}
void
Section::readJSONSectionImage(const boost::property_tree::ptree& _ptSection)
{
std::ostringstream buffer;
marshalFromJSON(_ptSection, buffer);
// -- Read contents into memory buffer --
m_bufferSize = buffer.tellp();
if (m_bufferSize == 0) {
std::string errMsg = XUtil::format("WARNING: Section '%s' content is empty. No data in the given JSON file.", getSectionKindAsString().c_str());
std::cout << errMsg.c_str() << std::endl;
return;
}
m_pBuffer = new char[m_bufferSize];
memcpy(m_pBuffer, buffer.str().c_str(), m_bufferSize);
}
void
Section::readXclBinBinary(std::fstream& _istream,
const boost::property_tree::ptree& _ptSection) {
// Some error checking
enum axlf_section_kind eKind = (enum axlf_section_kind)_ptSection.get<unsigned int>("Kind");
if (eKind != getSectionKind()) {
std::string errMsg = XUtil::format("ERROR: Unexpected section kind. Expected: %d, Read: %d", getSectionKind(), eKind);
}
if (m_pBuffer != nullptr) {
std::string errMsg = "ERROR: Binary buffer already exists.";
throw std::runtime_error(errMsg);
}
m_name = _ptSection.get<std::string>("Name");
boost::optional<const boost::property_tree::ptree&> ptPayload = _ptSection.get_child_optional("payload");
if (ptPayload.is_initialized()) {
XUtil::TRACE(XUtil::format("Reading in the section '%s' (%d) via metadata.", getSectionKindAsString().c_str(), (unsigned int)getSectionKind()));
readJSONSectionImage(ptPayload.get());
} else {
// We don't initialize the buffer via any metadata. Just read in the section as is
XUtil::TRACE(XUtil::format("Reading in the section '%s' (%d) as a image.", getSectionKindAsString().c_str(), (unsigned int)getSectionKind()));
m_bufferSize = XUtil::stringToUInt64(_ptSection.get<std::string>("Size"));
m_pBuffer = new char[m_bufferSize];
unsigned int offset = XUtil::stringToUInt64(_ptSection.get<std::string>("Offset"));
_istream.seekg(offset);
_istream.read(m_pBuffer, m_bufferSize);
if (_istream.gcount() != m_bufferSize) {
std::string errMsg = "ERROR: Input stream for the binary buffer is smaller then the expected size.";
throw std::runtime_error(errMsg);
}
}
XUtil::TRACE(XUtil::format("Adding Section: %s (%d)", getSectionKindAsString().c_str(), (unsigned int)getSectionKind()));
XUtil::TRACE(XUtil::format(" m_name: %s", m_name.c_str()));
XUtil::TRACE(XUtil::format(" m_size: %ld", m_bufferSize));
}
void
Section::getPayload(boost::property_tree::ptree& _pt) const {
marshalToJSON(m_pBuffer, m_bufferSize, _pt);
}
void
Section::marshalToJSON(char* _pDataSegment,
unsigned int _segmentSize,
boost::property_tree::ptree& _ptree) const {
// Do nothing
}
void
Section::appendToSectionMetadata(const boost::property_tree::ptree& _ptAppendData,
boost::property_tree::ptree& _ptToAppendTo)
{
std::string errMsg = "ERROR: The Section '" + getSectionKindAsString() + "' does not support appending metadata";
throw std::runtime_error(errMsg);
}
void
Section::marshalFromJSON(const boost::property_tree::ptree& _ptSection,
std::ostringstream& _buf) const {
XUtil::TRACE_PrintTree("Payload", _ptSection);
std::string errMsg = XUtil::format("ERROR: Section '%s' (%d) missing payload parser.", getSectionKindAsString().c_str(), (unsigned int)getSectionKind());
throw std::runtime_error(errMsg);
}
void
Section::readPayload(std::fstream& _istream, enum FormatType _eFormatType)
{
switch (_eFormatType) {
case FT_RAW:
{
axlf_section_header sectionHeader = (axlf_section_header){ 0 };
sectionHeader.m_sectionKind = getSectionKind();
sectionHeader.m_sectionOffset = 0;
_istream.seekg(0, _istream.end);
sectionHeader.m_sectionSize = _istream.tellg();
readXclBinBinary(_istream, sectionHeader);
break;
}
case FT_JSON:
{
// Bring the file into memory
_istream.seekg(0, _istream.end);
unsigned int fileSize = _istream.tellg();
std::unique_ptr<unsigned char> memBuffer(new unsigned char[fileSize]);
_istream.clear();
_istream.seekg(0);
_istream.read((char*)memBuffer.get(), fileSize);
XUtil::TRACE_BUF("Buffer", (char*)memBuffer.get(), fileSize);
// Convert the JSON file to a boost property tree
std::stringstream ss;
ss.write((char*) memBuffer.get(), fileSize);
boost::property_tree::ptree pt;
boost::property_tree::read_json(ss, pt);
// O.K. - Lint checking is done and write it to our buffer
readJSONSectionImage(pt);
break;
}
case FT_HTML:
// Do nothing
break;
case FT_TXT:
// Do nothing
break;
case FT_UNKNOWN:
// Do nothing
break;
case FT_UNDEFINED:
// Do nothing
break;
}
}
void
Section::readXclBinBinary(std::fstream& _istream, enum FormatType _eFormatType)
{
switch (_eFormatType) {
case FT_RAW:
{
axlf_section_header sectionHeader = (axlf_section_header){ 0 };
sectionHeader.m_sectionKind = getSectionKind();
sectionHeader.m_sectionOffset = 0;
_istream.seekg(0, _istream.end);
sectionHeader.m_sectionSize = _istream.tellg();
readXclBinBinary(_istream, sectionHeader);
break;
}
case FT_JSON:
{
// Bring the file into memory
_istream.seekg(0, _istream.end);
unsigned int fileSize = _istream.tellg();
std::unique_ptr<unsigned char> memBuffer(new unsigned char[fileSize]);
_istream.clear();
_istream.seekg(0);
_istream.read((char*)memBuffer.get(), fileSize);
XUtil::TRACE_BUF("Buffer", (char*)memBuffer.get(), fileSize);
// Convert the JSON file to a boost property tree
std::stringstream ss;
ss.write((char*) memBuffer.get(), fileSize);
boost::property_tree::ptree pt;
boost::property_tree::read_json(ss, pt);
readXclBinBinary(_istream, pt);
break;
}
case FT_HTML:
// Do nothing
break;
case FT_TXT:
// Do nothing
break;
case FT_UNKNOWN:
// Do nothing
break;
case FT_UNDEFINED:
// Do nothing
break;
}
}
void
Section::dumpContents(std::fstream& _ostream, enum FormatType _eFormatType) const
{
switch (_eFormatType) {
case FT_RAW:
{
writeXclBinSectionBuffer(_ostream);
break;
}
case FT_JSON:
{
boost::property_tree::ptree pt;
marshalToJSON(m_pBuffer, m_bufferSize, pt);
boost::property_tree::write_json(_ostream, pt, true /*Pretty print*/);
break;
}
case FT_HTML:
{
boost::property_tree::ptree pt;
marshalToJSON(m_pBuffer, m_bufferSize, pt);
_ostream << XUtil::format("<!DOCTYPE html><html><body><h1>Section: %s (%d)</h1><pre>", getSectionKindAsString().c_str(), getSectionKind()) << std::endl;
boost::property_tree::write_json(_ostream, pt, true /*Pretty print*/);
_ostream << "</pre></body></html>" << std::endl;
break;
}
case FT_UNKNOWN:
// Do nothing;
break;
case FT_TXT:
// Do nothing;
break;
case FT_UNDEFINED:
break;
}
}
void
Section::printHeader(std::ostream &_ostream) const
{
_ostream << "Section Header\n";
_ostream << " Type : '" << getSectionKindAsString() << "'" << std::endl;
_ostream << " Name : '" << getName() << "'" << std::endl;
_ostream << " Size : '" << getSize() << "' bytes" << std::endl;
}
bool
Section::doesSupportAddFormatType(FormatType _eFormatType) const
{
if (_eFormatType == FT_RAW) {
return true;
}
return false;
}
bool
Section::doesSupportDumpFormatType(FormatType _eFormatType) const
{
if (_eFormatType == FT_RAW) {
return true;
}
return false;
}
|
[bits 32]
[section .text]
global asm_rdtsc
global asm_cpuid
asm_rdtsc: ; void asm_rdtsc(int *high, int *low);
pushad
db 0x0F, 0x31 ; RDTSC
mov edi, [esp + 36]
mov dword [edi], EDX
mov edi, [esp + 40]
mov dword [edi], eax
popad
ret
asm_cpuid: ; void asm_cpuid(int id_eax, int id_ecx, int *eax, int *ebx, int *ecx, int *edx);
pushad
mov eax,[esp+36] ; id_eax
mov ecx,[esp+40] ; id_ecx
db 0x0F, 0xA2 ; CPUID
mov edi,[esp+44]
mov [edi], eax
mov edi,[esp+48]
mov dword [edi], ebx
mov edi,[esp+52]
mov dword [edi], ecx
mov edi,[esp+56]
mov dword [edi], edx
popad
ret
global asm_nop
asm_nop:
nop
ret
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 100100;
int T, n, a[maxn], f[maxn], g[maxn];
vector<int> ed[maxn];
void dfs(int t, int fa){
f[t] = g[t] = 0;
for(int i = 0; i < (int)ed[t].size(); ++i){
int v = ed[t][i];
if(v == fa) continue;
dfs(v, t);
f[t] ^= g[v];
g[t] ^= g[v];
}
f[t] ^= 1;
g[t] ^= f[t];
}
int main(){
scanf("%d", &T);
while(T--){
scanf("%d", &n);
for(int i = 1; i <= n; ++i) scanf("%d", a + i), ed[i].clear();
for(int i = 1; i < n; ++i){
int u, v;
scanf("%d%d", &u, &v);
ed[u].push_back(v);
ed[v].push_back(u);
}
dfs(1, 0);
int ans = 0;
for(int i = 1; i <= n; ++i)
if(a[i]) ans ^= f[i];
printf("%s\n", ans ? "Alice" : "Bob");
}
return 0;
}
|
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/04/Fill.asm
// Runs an infinite loop that listens to the keyboard input.
// When a key is pressed (any key), the program blackens the screen,
// i.e. writes "black" in every pixel;
// the screen should remain fully black as long as the key is pressed.
// When no key is pressed, the program clears the screen, i.e. writes
// "white" in every pixel;
// the screen should remain fully clear as long as no key is pressed.
// Put your code here.
// ****************************************************
// initialize screen parameters
@256 // 256 rows high
D=A
@rows
M=D
@32
D=A
@cols // 32 columns wide
M=D
// ****************************************************
(MAIN)
@KBD
D=M
// make screen black if any key is pressed
@BLACKSCREEN
D;JGT
// make screen white if no key is pressed
@WHITESCREEN
0;JMP
// END (MAIN)
// ****************************************************
(BLACKSCREEN)
@fillvalue
M=-1
@FILL
0;JMP
// END (BLACKSCREEN)
// ****************************************************
(WHITESCREEN)
@fillvalue
M=0
@FILL
0;JMP
// END (WHITESCREEN)
// ****************************************************
// fill screen uniformly
(FILL)
@SCREEN // SCREEN = 16384 (base address of the Hack screen)
D = A
@address // address = present working address
M = D
@i // row looping variable
M=-1
(LOOPROW) // outer loop: through the 256 rows in the screen
// advance row
@i
M=M+1
// check row loop condition
@i
D=M
@rows
D=D-M
@MAIN
D;JEQ
@j // column looping variable
M=-1
(LOOPCOL) // inner loop: through the 32 columns in each row
// advance column
@j
M=M+1
// check column loop condition
@j
D=M
@cols
D=D-M
@LOOPROW
D;JEQ
// apply fill
@fillvalue
D=M
@address
A=M // write to memory using a pointer
M=D
// update address
@address
M=M+1
@LOOPCOL
0;JMP
// END (FILL)
// **************************************************** |
db "TOUGH FISH@" ; species name
db "Its tough hide is"
next "a cover for its"
next "general lack of"
page "intelligence and"
next "maneuverability in"
next "the water.@"
|
_AgathaBeforeBattleText::
text "I am AGATHA of"
line "the ELITE FOUR!"
para "OAK's taken a lot"
line "of interest in"
cont "you, child!"
para "That old duff was"
line "once tough and"
cont "handsome! That"
cont "was decades ago!"
para "Now he just wants"
line "to fiddle with"
cont "his #DEX! He's"
cont "wrong! #MON"
cont "are for fighting!"
para $52, "! I'll show"
line "you how a real"
cont "trainer fights!"
done
_AgathaEndBattleText::
text "Oh ho!"
line "You're something"
cont "special, child!"
prompt
_AgathaAfterBattleText::
text "You win! I see"
line "what the old duff"
cont "sees in you now!"
para "I have nothing"
line "else to say! Run"
cont "along now, child!"
done
_AgathaDontRunAwayText::
text "Someone's voice:"
line "Don't run away!"
done
|
name "loader"
; this is a very basic example of a tiny operating system.
; directive to create boot file:
#make_boot#
; this is an os loader only!
;
; it can be loaded at the first sector of a floppy disk:
; cylinder: 0
; sector: 1
; head: 0
;=================================================
; how to test micro-operating system:
; 1. compile micro-os_loader.asm
; 2. compile micro-os_kernel.asm
; 3. compile writebin.asm
; 4. insert empty floppy disk to drive a:
; 5. from command prompt type:
; writebin loader.bin
; writebin kernel.bin /k
;=================================================
;
; The code in this file is supposed to load
; the kernel (micro-os_kernel.asm) and to pass control over it.
; The kernel code should be on floppy at:
; cylinder: 0
; sector: 2
; head: 0
; memory table (hex):
; -------------------------------
; 07c0:0000 | boot sector
; 07c0:01ff | (512 bytes)
; -------------------------------
; 07c0:0200 | stack
; 07c0:03ff | (255 words)
; -------------------------------
; 0800:0000 | kernel
; 0800:1400 |
; | (currently 5 kb,
; | 10 sectors are
; | loaded from
; | floppy)
; -------------------------------
; To test this program in real envirinment write it to floppy
; disk using compiled writebin.asm
; After sucessfully compilation of both files,
; type this from command prompt: writebin loader.bin
; Note: floppy disk boot record will be overwritten.
; the floppy will not be useable under windows/dos until
; you reformat it, data on floppy disk may be lost.
; use empty floppy disks only.
; micro-os_loader.asm file produced by this code should be less or
; equal to 512 bytes, since this is the size of the boot sector.
; boot record is loaded at 0000:7c00
org 7c00h
; initialize the stack:
mov ax, 07c0h
mov ss, ax
mov sp, 03feh ; top of the stack.
; set data segment:
xor ax, ax
mov ds, ax
; set default video mode 80x25:
mov ah, 00h
mov al, 03h
int 10h
; print welcome message:
lea si, msg
call print_string
;===================================
; load the kernel at 0800h:0000h
; 10 sectors starting at:
; cylinder: 0
; sector: 2
; head: 0
; BIOS passes drive number in dl,
; so it's not changed:
mov ah, 02h ; read function.
mov al, 10 ; sectors to read.
mov ch, 0 ; cylinder.
mov cl, 2 ; sector.
mov dh, 0 ; head.
; dl not changed! - drive number.
; es:bx points to receiving
; data buffer:
mov bx, 0800h
mov es, bx
mov bx, 0
; read!
int 13h
;===================================
; integrity check:
cmp es:[0000],0E9h ; first byte of kernel must be 0E9 (jmp).
je integrity_check_ok
; integrity check error
lea si, err
call print_string
; wait for any key...
mov ah, 0
int 16h
; store magic value at 0040h:0072h:
; 0000h - cold boot.
; 1234h - warm boot.
mov ax, 0040h
mov ds, ax
mov w.[0072h], 0000h ; cold boot.
jmp 0ffffh:0000h ; reboot!
;===================================
integrity_check_ok:
; pass control to kernel:
jmp 0800h:0000h
;===========================================
print_string proc near
push ax ; store registers...
push si ;
next_char:
mov al, [si]
cmp al, 0
jz printed
inc si
mov ah, 0eh ; teletype function.
int 10h
jmp next_char
printed:
pop si ; re-store registers...
pop ax ;
ret
print_string endp
;==== data section =====================
msg db "Loading...",0Dh,0Ah, 0
err db "invalid data at sector: 2, cylinder: 0, head: 0 - integrity check failed.", 0Dh,0Ah
db "refer to tutorial 11 - making your own operating system.", 0Dh,0Ah
db "System will reboot now. Press any key...", 0
;======================================
|
;NES hardware-dependent functions by Shiru (shiru@mail.ru)
;with improvements by VEG
;Feel free to do anything you want with this code, consider it Public Domain
; NOTE: Edits by cppchriscpp:
; - Added mmc1 bank swapping
; - Made the nmi and music_play methods support swapping to a set SOUND_BANK before reading data.
; - Added second split method with y split support from na_th_an's NESDev code
; - Messed with the original split method to make it trigger a little later.
; - Problematic PAL bugfix removed; only supporting NTSC with this engine.
; - Added reset method to reset system to initial state
; - Added a simple wait for sprite0 hit, to allow us to do C things.
; - Added a handler to nmi to allow switching chr banks at the very start of nmi (mixed with functions in bank_helpers)
;modified to work with the FamiTracker music driver
.export _pal_all,_pal_bg,_pal_spr,_pal_col,_pal_clear
.export _pal_bright,_pal_spr_bright,_pal_bg_bright
.export _ppu_off,_ppu_on_all,_ppu_on_bg,_ppu_on_spr,_ppu_mask,_ppu_system
.export _oam_clear,_oam_size,_oam_spr,_oam_meta_spr,_oam_hide_rest
.export _ppu_wait_frame,_ppu_wait_nmi
.export _scroll,_split
.export _bank_spr,_bank_bg
.export _vram_read,_vram_write
.export _music_play,_music_stop,_music_pause, _music_play_nonstop
.export _sfx_play
.export _pad_poll,_pad_trigger,_pad_state
.export _rand8,_rand16,_set_rand
.export _vram_adr,_vram_put,_vram_fill,_vram_inc,_vram_unrle
.export _set_vram_update,_flush_vram_update
.export _memcpy,_memfill,_delay
.export nmi_update
.export _split_y,_reset,_wait_for_sprite0_hit
;NMI handler
nmi:
; Due to quirks of the MMC1 mapper, there's a chance this flips when we're in the middle of switching PRG banks.
; If this happens, we need to catch it, quickly return to what we were doing, then re-trigger the nmi update.
pha
lda BANK_WRITE_IP
cmp #1
bne @continue
; If we were in the middle of switching banks, set a flag to check later...
inc BANK_WRITE_IP
pla
; then return from the interrupt without doing anything else.
rti
@continue:
; Not in the middle of a bank switch, so run the nmi_update method as normal.
pla
jsr nmi_update
rti
nmi_update:
pha
txa
pha
tya
pha
lda <PPU_MASK_VAR ;if rendering is disabled, do not access the VRAM at all
and #%00011000
bne @doUpdate
jmp @skipAll
@doUpdate:
lda nmiChrTileBank
cmp #NO_CHR_BANK
beq @no_chr_chg
jsr _set_chr_bank_0
@no_chr_chg:
lda #>OAM_BUF ;update OAM
sta PPU_OAM_DMA
lda <PAL_UPDATE ;update palette if needed
bne @updPal
jmp @updVRAM
@updPal:
ldx #0
stx <PAL_UPDATE
lda #$3f
sta PPU_ADDR
stx PPU_ADDR
ldy PAL_BUF ;background color, remember it in X
lda (PAL_BG_PTR),y
sta PPU_DATA
tax
.repeat 3,I
ldy PAL_BUF+1+I
lda (PAL_BG_PTR),y
sta PPU_DATA
.endrepeat
.repeat 3,J
stx PPU_DATA ;background color
.repeat 3,I
ldy PAL_BUF+5+(J*4)+I
lda (PAL_BG_PTR),y
sta PPU_DATA
.endrepeat
.endrepeat
.repeat 4,J
stx PPU_DATA ;background color
.repeat 3,I
ldy PAL_BUF+17+(J*4)+I
lda (PAL_SPR_PTR),y
sta PPU_DATA
.endrepeat
.endrepeat
@updVRAM:
lda <VRAM_UPDATE
beq @skipUpd
lda #0
sta <VRAM_UPDATE
lda <NAME_UPD_ENABLE
beq @skipUpd
jsr _flush_vram_update_nmi
@skipUpd:
lda #0
sta PPU_ADDR
sta PPU_ADDR
lda <SCROLL_X
sta PPU_SCROLL
lda <SCROLL_Y
sta PPU_SCROLL
lda <PPU_CTRL_VAR
sta PPU_CTRL
@skipAll:
lda <PPU_MASK_VAR
sta PPU_MASK
inc <FRAME_CNT1
inc <FRAME_CNT2
lda <FRAME_CNT2
cmp #6
bne @skipNtsc
lda #0
sta <FRAME_CNT2
@skipNtsc:
; Bank swapping time! Switch to the music bank for sfx, etc...
lda BP_BANK
sta NMI_BANK_TEMP
lda #SOUND_BANK
sta BP_BANK
jsr _set_prg_bank_raw
;play music, the code is modified to put data into output buffer instead of APU registers
lda <MUSIC_PLAY
ror
bcc :+
jsr ft_music_play
jmp :++
:
lda #$30 ;mute channels when music does not play
sta <BUF_4000
sta <BUF_4004
sta <BUF_400C
lda #$00
sta <BUF_4008
:
;process all sound effect streams
.if(FT_SFX_ENABLE)
.if FT_SFX_STREAMS>0
ldx #FT_SFX_CH0
jsr _FT2SfxUpdate
.endif
.if FT_SFX_STREAMS>1
ldx #FT_SFX_CH1
jsr _FT2SfxUpdate
.endif
.if FT_SFX_STREAMS>2
ldx #FT_SFX_CH2
jsr _FT2SfxUpdate
.endif
.if FT_SFX_STREAMS>3
ldx #FT_SFX_CH3
jsr _FT2SfxUpdate
.endif
.endif
;send data from the output buffer to the APU
lda <BUF_4000
sta $4000
lda <BUF_4001
sta $4001
lda <BUF_4002
sta $4002
lda <BUF_4003
cmp <PREV_4003
beq :+
sta <PREV_4003
sta $4003
:
lda <BUF_4004
sta $4004
lda <BUF_4005
sta $4005
lda <BUF_4006
sta $4006
lda <BUF_4007
cmp <PREV_4007
beq :+
sta <PREV_4007
sta $4007
:
lda <BUF_4008
sta $4008
lda <BUF_4009
sta $4009
lda <BUF_400A
sta $400A
lda <BUF_400B
sta $400B
lda <BUF_400C
sta $400C
lda <BUF_400D
sta $400D
lda <BUF_400E
sta $400E
lda <BUF_400F
sta $400F
lda NMI_BANK_TEMP
sta BP_BANK
jsr _set_prg_bank_raw
pla
tay
pla
tax
pla
irq:
rts
;famitone sound effects code and structures
FT_VARS=FT_BASE_ADR
.if(FT_PAL_SUPPORT)
.if(FT_NTSC_SUPPORT)
FT_PITCH_FIX = (FT_PAL_SUPPORT|FT_NTSC_SUPPORT) ;add PAL/NTSC pitch correction code only when both modes are enabled
.endif
.endif
;zero page variables
FT_TEMP_PTR = FT_TEMP ;word
FT_TEMP_PTR_L = FT_TEMP_PTR+0
FT_TEMP_PTR_H = FT_TEMP_PTR+1
FT_TEMP_VAR1 = FT_TEMP+2
;sound effect stream variables, 2 bytes and 15 bytes per stream
;when sound effects are disabled, this memory is not used
FT_PAL_ADJUST = FT_VARS+0
FT_SFX_ADR_L = FT_VARS+1
FT_SFX_ADR_H = FT_VARS+2
FT_SFX_BASE_ADR = FT_VARS+3
FT_SFX_STRUCT_SIZE = 15
FT_SFX_REPEAT = FT_SFX_BASE_ADR+0
FT_SFX_PTR_L = FT_SFX_BASE_ADR+1
FT_SFX_PTR_H = FT_SFX_BASE_ADR+2
FT_SFX_OFF = FT_SFX_BASE_ADR+3
FT_SFX_BUF = FT_SFX_BASE_ADR+4 ;11 bytes
;aliases for sound effect channels to use in user calls
FT_SFX_CH0 = FT_SFX_STRUCT_SIZE*0
FT_SFX_CH1 = FT_SFX_STRUCT_SIZE*1
FT_SFX_CH2 = FT_SFX_STRUCT_SIZE*2
FT_SFX_CH3 = FT_SFX_STRUCT_SIZE*3
.if(FT_SFX_ENABLE)
;------------------------------------------------------------------------------
; init sound effects player, set pointer to data
; in: X,Y is address of sound effects data
;------------------------------------------------------------------------------
FamiToneSfxInit:
stx <TEMP+0
sty <TEMP+1
ldy #0
; @cppchriscpp change:
; Disable the famitracker PAL features... it has a weird bug where if I disable PAL, this var
; is no longer defined, and ca65 does not like that.
; .if(FT_PITCH_FIX)
; lda FT_PAL_ADJUST ;add 2 to the sound list pointer for PAL
; bne @ntsc
; iny
; iny
@ntsc:
; .endif
lda (TEMP),y ;read and store pointer to the effects list
sta FT_SFX_ADR_L
iny
lda (TEMP),y
sta FT_SFX_ADR_H
ldx #FT_SFX_CH0 ;init all the streams
@set_channels:
jsr _FT2SfxClearChannel
txa
clc
adc #FT_SFX_STRUCT_SIZE
tax
cpx #FT_SFX_CH0+FT_SFX_STRUCT_SIZE*FT_SFX_STREAMS
bne @set_channels
rts
;internal routine, clears output buffer of a sound effect
;in: A is 0
; X is offset of sound effect stream
_FT2SfxClearChannel:
lda #0
sta FT_SFX_PTR_H,x ;this stops the effect
sta FT_SFX_REPEAT,x
sta FT_SFX_OFF,x
sta FT_SFX_BUF+6,x ;mute triangle
lda #$30
sta FT_SFX_BUF+0,x ;mute pulse1
sta FT_SFX_BUF+3,x ;mute pulse2
sta FT_SFX_BUF+9,x ;mute noise
rts
;------------------------------------------------------------------------------
; play sound effect
; in: A is a number of the sound effect 0..127
; X is offset of sound effect channel, should be FT_SFX_CH0..FT_SFX_CH3
;------------------------------------------------------------------------------
FamiToneSfxPlay:
asl a ;get offset in the effects list
tay
jsr _FT2SfxClearChannel ;stops the effect if it plays
lda FT_SFX_ADR_L
sta <TEMP+0
lda FT_SFX_ADR_H
sta <TEMP+1
lda (TEMP),y ;read effect pointer from the table
sta FT_SFX_PTR_L,x ;store it
iny
lda (TEMP),y
sta FT_SFX_PTR_H,x ;this write enables the effect
rts
;internal routine, update one sound effect stream
;in: X is offset of sound effect stream
_FT2SfxUpdate:
lda FT_SFX_REPEAT,x ;check if repeat counter is not zero
beq @no_repeat
dec FT_SFX_REPEAT,x ;decrement and return
bne @update_buf ;just mix with output buffer
@no_repeat:
lda FT_SFX_PTR_H,x ;check if MSB of the pointer is not zero
bne @sfx_active
rts ;return otherwise, no active effect
@sfx_active:
sta <FT_TEMP_PTR_H ;load effect pointer into temp
lda FT_SFX_PTR_L,x
sta <FT_TEMP_PTR_L
ldy FT_SFX_OFF,x
clc
@read_byte:
lda (FT_TEMP_PTR),y ;read byte of effect
bmi @get_data ;if bit 7 is set, it is a register write
beq @eof
iny
sta FT_SFX_REPEAT,x ;if bit 7 is reset, it is number of repeats
tya
sta FT_SFX_OFF,x
jmp @update_buf
@get_data:
iny
stx <FT_TEMP_VAR1 ;it is a register write
adc <FT_TEMP_VAR1 ;get offset in the effect output buffer
and #$7f
tax
lda (FT_TEMP_PTR),y ;read value
iny
sta FT_SFX_BUF,x ;store into output buffer
ldx <FT_TEMP_VAR1
jmp @read_byte ;and read next byte
@eof:
sta FT_SFX_PTR_H,x ;mark channel as inactive
@update_buf:
lda <BUF_4000 ;compare effect output buffer with main output buffer
and #$0f ;if volume of pulse 1 of effect is higher than that of the
sta <FT_TEMP_VAR1 ;main buffer, overwrite the main buffer value with the new one
lda FT_SFX_BUF+0,x
and #$0f
cmp <FT_TEMP_VAR1
bcc @no_pulse1
lda FT_SFX_BUF+0,x
sta <BUF_4000
lda FT_SFX_BUF+1,x
sta <BUF_4002
lda FT_SFX_BUF+2,x
sta <BUF_4003
@no_pulse1:
lda <BUF_4004 ;same for pulse 2
and #$0f
sta <FT_TEMP_VAR1
lda FT_SFX_BUF+3,x
and #$0f
cmp <FT_TEMP_VAR1
bcc @no_pulse2
lda FT_SFX_BUF+3,x
sta <BUF_4004
lda FT_SFX_BUF+4,x
sta <BUF_4006
lda FT_SFX_BUF+5,x
sta <BUF_4007
@no_pulse2:
lda FT_SFX_BUF+6,x ;overwrite triangle of main output buffer if it is active
beq @no_triangle
sta <BUF_4008
lda FT_SFX_BUF+7,x
sta <BUF_400A
lda FT_SFX_BUF+8,x
sta <BUF_400B
@no_triangle:
lda <BUF_400C ;same as for pulse 1 and 2, but for noise
and #$0f
sta <FT_TEMP_VAR1
lda FT_SFX_BUF+9,x
and #$0f
cmp <FT_TEMP_VAR1
bcc @no_noise
lda FT_SFX_BUF+9,x
sta <BUF_400C
lda FT_SFX_BUF+10,x
sta <BUF_400E
@no_noise:
rts
.endif
;void __fastcall__ pal_all(const char *data);
_pal_all:
sta <PTR
stx <PTR+1
ldx #$00
lda #$20
pal_copy:
sta <LEN
ldy #$00
@0:
lda (PTR),y
sta PAL_BUF,x
inx
iny
dec <LEN
bne @0
inc <PAL_UPDATE
rts
;void __fastcall__ pal_bg(const char *data);
_pal_bg:
sta <PTR
stx <PTR+1
ldx #$00
lda #$10
bne pal_copy ;bra
;void __fastcall__ pal_spr(const char *data);
_pal_spr:
sta <PTR
stx <PTR+1
ldx #$10
txa
bne pal_copy ;bra
;void __fastcall__ pal_col(unsigned char index,unsigned char color);
_pal_col:
sta <PTR
jsr popa
and #$1f
tax
lda <PTR
sta PAL_BUF,x
inc <PAL_UPDATE
rts
;void __fastcall__ pal_clear(void);
_pal_clear:
lda #$0f
ldx #0
@1:
sta PAL_BUF,x
inx
cpx #$20
bne @1
stx <PAL_UPDATE
rts
;void __fastcall__ pal_spr_bright(unsigned char bright);
_pal_spr_bright:
tax
lda palBrightTableL,x
sta <PAL_SPR_PTR
lda palBrightTableH,x ;MSB is never zero
sta <PAL_SPR_PTR+1
sta <PAL_UPDATE
rts
;void __fastcall__ pal_bg_bright(unsigned char bright);
_pal_bg_bright:
tax
lda palBrightTableL,x
sta <PAL_BG_PTR
lda palBrightTableH,x ;MSB is never zero
sta <PAL_BG_PTR+1
sta <PAL_UPDATE
rts
;void __fastcall__ pal_bright(unsigned char bright);
_pal_bright:
jsr _pal_spr_bright
txa
jmp _pal_bg_bright
;void __fastcall__ ppu_off(void);
_ppu_off:
lda <PPU_MASK_VAR
and #%11100111
sta <PPU_MASK_VAR
jmp _ppu_wait_nmi
;void __fastcall__ ppu_on_all(void);
_ppu_on_all:
lda <PPU_MASK_VAR
ora #%00011000
ppu_onoff:
sta <PPU_MASK_VAR
jmp _ppu_wait_nmi
;void __fastcall__ ppu_on_bg(void);
_ppu_on_bg:
lda <PPU_MASK_VAR
ora #%00001000
bne ppu_onoff ;bra
;void __fastcall__ ppu_on_spr(void);
_ppu_on_spr:
lda <PPU_MASK_VAR
ora #%00010000
bne ppu_onoff ;bra
;void __fastcall__ ppu_mask(unsigned char mask);
_ppu_mask:
sta <PPU_MASK_VAR
rts
;unsigned char __fastcall__ ppu_system(void);
_ppu_system:
lda <NTSC_MODE
rts
;void __fastcall__ oam_clear(void);
_oam_clear:
ldx #0
lda #$ff
@1:
sta OAM_BUF,x
inx
inx
inx
inx
bne @1
rts
;void __fastcall__ oam_size(unsigned char size);
_oam_size:
asl a
asl a
asl a
asl a
asl a
and #$20
sta <TEMP
lda <PPU_CTRL_VAR
and #$df
ora <TEMP
sta <PPU_CTRL_VAR
rts
;unsigned char __fastcall__ oam_spr(unsigned char x,unsigned char y,unsigned char chrnum,unsigned char attr,unsigned char sprid);
_oam_spr:
tax
ldy #0 ;four popa calls replacement
lda (sp),y
iny
sta OAM_BUF+2,x
lda (sp),y
iny
sta OAM_BUF+1,x
lda (sp),y
iny
sta OAM_BUF+0,x
lda (sp),y
sta OAM_BUF+3,x
lda <sp
clc
adc #4
sta <sp
bcc @1
inc <sp+1
@1:
txa
clc
adc #4
rts
;unsigned char __fastcall__ oam_meta_spr(unsigned char x,unsigned char y,unsigned char sprid,const unsigned char *data);
_oam_meta_spr:
sta <PTR
stx <PTR+1
ldy #2 ;three popa calls replacement, performed in reversed order
lda (sp),y
dey
sta <SCRX
lda (sp),y
dey
sta <SCRY
lda (sp),y
tax
@1:
lda (PTR),y ;x offset
cmp #$80
beq @2
iny
clc
adc <SCRX
sta OAM_BUF+3,x
lda (PTR),y ;y offset
iny
clc
adc <SCRY
sta OAM_BUF+0,x
lda (PTR),y ;tile
iny
sta OAM_BUF+1,x
lda (PTR),y ;attribute
iny
sta OAM_BUF+2,x
inx
inx
inx
inx
jmp @1
@2:
lda <sp
adc #2 ;carry is always set here, so it adds 3
sta <sp
bcc @3
inc <sp+1
@3:
txa
rts
;void __fastcall__ oam_hide_rest(unsigned char sprid);
_oam_hide_rest:
tax
lda #240
@1:
sta OAM_BUF,x
inx
inx
inx
inx
bne @1
rts
;void __fastcall__ ppu_wait_frame(void);
_ppu_wait_frame:
lda #1
sta <VRAM_UPDATE
lda <FRAME_CNT1
@1:
cmp <FRAME_CNT1
beq @1
lda <NTSC_MODE
beq @3
@2:
lda <FRAME_CNT2
cmp #5
beq @2
@3:
rts
;void __fastcall__ ppu_wait_nmi(void);
_ppu_wait_nmi:
lda #1
sta <VRAM_UPDATE
lda <FRAME_CNT1
@1:
cmp <FRAME_CNT1
beq @1
rts
;void __fastcall__ vram_unrle(const unsigned char *data);
_vram_unrle:
tay
stx <RLE_HIGH
lda #0
sta <RLE_LOW
lda (RLE_LOW),y
sta <RLE_TAG
iny
bne @1
inc <RLE_HIGH
@1:
lda (RLE_LOW),y
iny
bne @11
inc <RLE_HIGH
@11:
cmp <RLE_TAG
beq @2
sta PPU_DATA
sta <RLE_BYTE
bne @1
@2:
lda (RLE_LOW),y
beq @4
iny
bne @21
inc <RLE_HIGH
@21:
tax
lda <RLE_BYTE
@3:
sta PPU_DATA
dex
bne @3
beq @1
@4:
rts
;void __fastcall__ scroll(unsigned int x,unsigned int y);
_scroll:
sta <TEMP
txa
; bne @1
lda <TEMP
cmp #240
bcs @1
sta <SCROLL_Y
lda #0
sta <TEMP
beq @2 ;bra
@1:
sec
lda <TEMP
sbc #240
sta <SCROLL_Y
lda #2
sta <TEMP
@2:
jsr popax
sta <SCROLL_X
txa
and #$01
ora <TEMP
sta <TEMP
lda <PPU_CTRL_VAR
and #$fc
ora <TEMP
sta <PPU_CTRL_VAR
rts
;;void __fastcall__ split(unsigned int x,unsigned int y);
_split:
jsr popax
sta <SCROLL_X1
txa
and #$01
sta <TEMP
lda <PPU_CTRL_VAR
and #$fc
ora <TEMP
sta <PPU_CTRL_VAR1
@3:
bit PPU_STATUS
bvs @3
@4:
bit PPU_STATUS
bvc @4
; Wait a few cycles to align with the *next* line.
; @cppchriscpp hack
ldx #0
@looper:
inx
cpx #44
bne @looper
lda <SCROLL_X1
sta PPU_SCROLL
lda #0
sta PPU_SCROLL
lda <PPU_CTRL_VAR1
sta PPU_CTRL
rts
;;void __fastcall__ wait_for_sprite0_hit();
_wait_for_sprite0_hit:
lda <PPU_CTRL_VAR
and #$fc
ora <TEMP
sta <PPU_CTRL_VAR1
@3:
bit PPU_STATUS
bvs @3
@4:
bit PPU_STATUS
bvc @4
; Wait a few cycles to align with the *next* line.
; @cppchriscpp hack
ldx #0
@looper:
inx
cpx #44
bne @looper
rts
;;void __fastcall__ split_y(unsigned int x,unsigned int y);
; Using na_tha_an's trickery for y scroll from here: https://forums.nesdev.com/viewtopic.php?f=2&t=16435
; Thanks dude!
; Extract SCROLL_Y1, SCROLL_X1, WRITE1 from parameters.
_split_y:
sta <TEMP
txa
bne @1
lda <TEMP
cmp #240
bcs @1
sta <SCROLL_Y1
lda #0
sta <TEMP
beq @2 ;bra
@1:
sec
lda <TEMP
sbc #240
sta <SCROLL_Y1
lda #8 ;; Bit 3
sta <TEMP
@2:
jsr popax
sta <SCROLL_X1
txa
and #$01
asl a
asl a ;; Bit 2
ora <TEMP ;; From Y
sta <WRITE1 ;; Store!
; Calculate WRITE2 = ((Y & $F8) << 2) | (X >> 3)
lda <SCROLL_Y1
and #$F8
asl a
asl a
sta <TEMP ;; TEMP = (Y & $F8) << 2
lda <SCROLL_X1
lsr a
lsr a
lsr a ;; A = (X >> 3)
ora <TEMP ;; A = (X >> 3) | ((Y & $F8) << 2)
sta <WRITE2 ;; Store!
; Wait for sprite 0 hit
@3:
bit PPU_STATUS
bvs @3
@4:
bit PPU_STATUS
bvc @4
; Wait a few cycles to align with the *next* line.
; @cppchriscpp hack
ldx #0
@looper:
inx
cpx #44
bne @looper
; Set scroll value
lda PPU_STATUS
lda <WRITE1
sta PPU_ADDR
lda <SCROLL_Y1
sta PPU_SCROLL
lda <SCROLL_X1
ldx <WRITE2
sta PPU_SCROLL
stx PPU_ADDR
rts
;void __fastcall__ bank_spr(unsigned char n);
_bank_spr:
and #$01
asl a
asl a
asl a
sta <TEMP
lda <PPU_CTRL_VAR
and #%11110111
ora <TEMP
sta <PPU_CTRL_VAR
rts
;void __fastcall__ bank_bg(unsigned char n);
_bank_bg:
and #$01
asl a
asl a
asl a
asl a
sta <TEMP
lda <PPU_CTRL_VAR
and #%11101111
ora <TEMP
sta <PPU_CTRL_VAR
rts
;void __fastcall__ vram_read(unsigned char *dst,unsigned int size);
_vram_read:
sta <TEMP
stx <TEMP+1
jsr popax
sta <TEMP+2
stx <TEMP+3
lda PPU_DATA
ldy #0
@1:
lda PPU_DATA
sta (TEMP+2),y
inc <TEMP+2
bne @2
inc <TEMP+3
@2:
lda <TEMP
bne @3
dec <TEMP+1
@3:
dec <TEMP
lda <TEMP
ora <TEMP+1
bne @1
rts
;void __fastcall__ vram_write(unsigned char *src,unsigned int size);
_vram_write:
sta <TEMP
stx <TEMP+1
jsr popax
sta <TEMP+2
stx <TEMP+3
ldy #0
@1:
lda (TEMP+2),y
sta PPU_DATA
inc <TEMP+2
bne @2
inc <TEMP+3
@2:
lda <TEMP
bne @3
dec <TEMP+1
@3:
dec <TEMP
lda <TEMP
ora <TEMP+1
bne @1
rts
;void __fastcall__ music_play(unsigned char song);
_music_play:
; @cppchriscpp Edit - forcing a swap to the music bank
; Need to temporarily swap banks to pull this off.
tax ; Put our song into x for a moment...
; Being extra careful and setting BP_BANK to ours in case an nmi fires while we're doing this.
lda BP_BANK
pha
lda #SOUND_BANK
sta BP_BANK
mmc1_register_write MMC1_PRG
txa ; bring back the song number!
ldx #<music_data
stx <ft_music_addr+0
ldx #>music_data
stx <ft_music_addr+1
ldx <NTSC_MODE
jsr ft_music_init
lda #1
sta <MUSIC_PLAY
; Remember when we stored the old bank into BP_BANK and swapped? Time to roll back.
pla
sta BP_BANK
mmc1_register_write MMC1_PRG
rts
_music_play_nonstop:
jmp _music_play
; @cppchriscpp Edit - forcing a swap to the music bank
; @cppchriscpp Edit 2 - Duplicating this function to not stop the music on swap when called this way. Same signature
; Need to temporarily swap banks to pull this off.
tax ; Put our song into x for a moment...
; Being extra careful and setting BP_BANK to ours in case an nmi fires while we're doing this.
lda BP_BANK
pha
lda #SOUND_BANK
sta BP_BANK
mmc1_register_write MMC1_PRG
txa ; bring back the song number!
ldx #<music_data
stx <ft_music_addr+0
ldx #>music_data
stx <ft_music_addr+1
ldx <NTSC_MODE
jsr ft_music_init_b
lda #1
sta <MUSIC_PLAY
; Remember when we stored the old bank into BP_BANK and swapped? Time to roll back.
pla
sta BP_BANK
mmc1_register_write MMC1_PRG
rts
;void __fastcall__ music_stop(void);
_music_stop:
ldx #<music_dummy_data
stx <ft_music_addr+0
ldx #>music_dummy_data
stx <ft_music_addr+1
lda #0
ldx <NTSC_MODE
jsr ft_music_init
lda #0
sta <MUSIC_PLAY
rts
;void __fastcall__ music_pause(unsigned char pause);
_music_pause:
inc <MUSIC_PLAY
rts
;void __fastcall__ sfx_play(unsigned char sound,unsigned char channel);
_sfx_play:
.if(FT_SFX_ENABLE)
; TODO: Should I be blocking interrupts while doing weird bank stuff?
; @cppchriscpp Edit - forcing a swap to the music bank
; Need to temporarily swap banks to pull this off.
tay ; Put our song into y for a moment...
; Being extra careful and setting BP_BANK to ours in case an nmi fires while we're doing this.
lda BP_BANK
pha
lda #SOUND_BANK
sta BP_BANK
mmc1_register_write MMC1_PRG
tya ; bring back the song number!
and #$03
tax
lda @sfxPriority,x
tax
jsr popa
jsr FamiToneSfxPlay
; Remember when we stored the old bank into BP_BANK and swapped? Time to roll back.
pla
sta BP_BANK
mmc1_register_write MMC1_PRG
rts
@sfxPriority:
.byte FT_SFX_CH0,FT_SFX_CH1,FT_SFX_CH2,FT_SFX_CH3
.else
rts
.endif
;unsigned char __fastcall__ pad_poll(unsigned char pad);
_pad_poll:
tay
ldx #0
@padPollPort:
lda #1
sta CTRL_PORT1
lda #0
sta CTRL_PORT1
lda #8
sta <TEMP
@padPollLoop:
lda CTRL_PORT1,y
lsr a
ror <PAD_BUF,x
dec <TEMP
bne @padPollLoop
inx
cpx #3
bne @padPollPort
lda <PAD_BUF
cmp <PAD_BUF+1
beq @done
cmp <PAD_BUF+2
beq @done
lda <PAD_BUF+1
@done:
sta <PAD_STATE,y
tax
eor <PAD_STATEP,y
and <PAD_STATE ,y
sta <PAD_STATET,y
txa
sta <PAD_STATEP,y
rts
;unsigned char __fastcall__ pad_trigger(unsigned char pad);
_pad_trigger:
pha
jsr _pad_poll
pla
tax
lda <PAD_STATET,x
rts
;unsigned char __fastcall__ pad_state(unsigned char pad);
_pad_state:
tax
lda <PAD_STATE,x
rts
;unsigned char __fastcall__ rand8(void);
;Galois random generator, found somewhere
;out: A random number 0..255
rand1:
lda <RAND_SEED
asl a
bcc @1
eor #$cf
@1:
sta <RAND_SEED
rts
rand2:
lda <RAND_SEED+1
asl a
bcc @1
eor #$d7
@1:
sta <RAND_SEED+1
rts
_rand8:
jsr rand1
jsr rand2
adc <RAND_SEED
rts
;unsigned int __fastcall__ rand16(void);
_rand16:
jsr rand1
tax
jsr rand2
rts
;void __fastcall__ set_rand(unsigned char seed);
_set_rand:
sta <RAND_SEED
stx <RAND_SEED+1
rts
;void __fastcall__ set_vram_update(unsigned char *buf);
_set_vram_update:
sta <NAME_UPD_ADR+0
stx <NAME_UPD_ADR+1
ora <NAME_UPD_ADR+1
sta <NAME_UPD_ENABLE
rts
;void __fastcall__ flush_vram_update(unsigned char *buf);
_flush_vram_update:
sta <NAME_UPD_ADR+0
stx <NAME_UPD_ADR+1
_flush_vram_update_nmi:
ldy #0
@updName:
lda (NAME_UPD_ADR),y
iny
cmp #$40 ;is it a non-sequental write?
bcs @updNotSeq
sta PPU_ADDR
lda (NAME_UPD_ADR),y
iny
sta PPU_ADDR
lda (NAME_UPD_ADR),y
iny
sta PPU_DATA
jmp @updName
@updNotSeq:
tax
lda <PPU_CTRL_VAR
cpx #$80 ;is it a horizontal or vertical sequence?
bcc @updHorzSeq
cpx #$ff ;is it end of the update?
beq @updDone
@updVertSeq:
ora #$04
bne @updNameSeq ;bra
@updHorzSeq:
and #$fb
@updNameSeq:
sta PPU_CTRL
txa
and #$3f
sta PPU_ADDR
lda (NAME_UPD_ADR),y
iny
sta PPU_ADDR
lda (NAME_UPD_ADR),y
iny
tax
@updNameLoop:
lda (NAME_UPD_ADR),y
iny
sta PPU_DATA
dex
bne @updNameLoop
lda <PPU_CTRL_VAR
sta PPU_CTRL
jmp @updName
@updDone:
rts
;void __fastcall__ vram_adr(unsigned int adr);
_vram_adr:
stx PPU_ADDR
sta PPU_ADDR
rts
;void __fastcall__ vram_put(unsigned char n);
_vram_put:
sta PPU_DATA
rts
;void __fastcall__ vram_fill(unsigned char n,unsigned int len);
_vram_fill:
sta <LEN
stx <LEN+1
jsr popa
ldx <LEN+1
beq @2
ldx #0
@1:
sta PPU_DATA
dex
bne @1
dec <LEN+1
bne @1
@2:
ldx <LEN
beq @4
@3:
sta PPU_DATA
dex
bne @3
@4:
rts
;void __fastcall__ vram_inc(unsigned char n);
_vram_inc:
ora #0
beq @1
lda #$04
@1:
sta <TEMP
lda <PPU_CTRL_VAR
and #$fb
ora <TEMP
sta <PPU_CTRL_VAR
sta PPU_CTRL
rts
;void __fastcall__ memcpy(void *dst,void *src,unsigned int len);
_memcpy:
sta <LEN
stx <LEN+1
jsr popax
sta <SRC
stx <SRC+1
jsr popax
sta <DST
stx <DST+1
ldx #0
@1:
lda <LEN+1
beq @2
jsr @3
dec <LEN+1
inc <SRC+1
inc <DST+1
jmp @1
@2:
ldx <LEN
beq @5
@3:
ldy #0
@4:
lda (SRC),y
sta (DST),y
iny
dex
bne @4
@5:
rts
;void __fastcall__ memfill(void *dst,unsigned char value,unsigned int len);
_memfill:
sta <LEN
stx <LEN+1
jsr popa
sta <TEMP
jsr popax
sta <DST
stx <DST+1
ldx #0
@1:
lda <LEN+1
beq @2
jsr @3
dec <LEN+1
inc <DST+1
jmp @1
@2:
ldx <LEN
beq @5
@3:
ldy #0
lda <TEMP
@4:
sta (DST),y
iny
dex
bne @4
@5:
rts
;void __fastcall__ delay(unsigned char frames);
_delay:
tax
@1:
jsr _ppu_wait_nmi
dex
bne @1
rts
;void __fastcall__ reset();
_reset:
jmp _exit
palBrightTableL:
.byte <palBrightTable0,<palBrightTable1,<palBrightTable2
.byte <palBrightTable3,<palBrightTable4,<palBrightTable5
.byte <palBrightTable6,<palBrightTable7,<palBrightTable8
palBrightTableH:
.byte >palBrightTable0,>palBrightTable1,>palBrightTable2
.byte >palBrightTable3,>palBrightTable4,>palBrightTable5
.byte >palBrightTable6,>palBrightTable7,>palBrightTable8
palBrightTable0:
.byte $0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f ;black
palBrightTable1:
.byte $0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f
palBrightTable2:
.byte $0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f
palBrightTable3:
.byte $0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f,$0f
palBrightTable4:
.byte $00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0f,$0f,$0f ;normal colors
palBrightTable5:
.byte $10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$1a,$1b,$1c,$00,$00,$00
palBrightTable6:
.byte $10,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$10,$10,$10 ;$10 because $20 is the same as $30
palBrightTable7:
.byte $30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$20,$20,$20
palBrightTable8:
.byte $30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30 ;white
.byte $30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30
.byte $30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30
.byte $30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30,$30
; .include "famitone2.s" |
;page 95 sum of an integer array
.model small
.stack 100h
.data
intarray dw 200h,100h,300h,600h
.code
extrn clrscr:proc, writeint:proc
main proc
mov ax,0 ;zero accumulator
mov di,offset intarray ;address of intarray start
mov cx,4 ;number of integers
read_int:
add ax,[di] ;add integer to accum
add di,2 ;point to next integer
loop read_int ;repeat until cx=0
call clrscr
mov bx,10 ;radix of number to write
call writeint
mov ax,4c00h
int 21h
main endp
end main
|
db 0 ; species ID placeholder
db 50, 50, 40, 50, 30, 30
; hp atk def spd sat sdf
db ICE, GROUND ; type
db 225 ; catch rate
db 78 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F50 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/swinub/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_SLOW ; growth rate
dn EGG_GROUND, EGG_GROUND ; egg groups
; tm/hm learnset
tmhm HEADBUTT, CURSE, ROAR, TOXIC, ROCK_SMASH, HIDDEN_POWER, SNORE, BLIZZARD, ICY_WIND, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, EARTHQUAKE, RETURN, MUD_SLAP, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, DEFENSE_CURL, DETECT, REST, ATTRACT, STRENGTH, ICE_BEAM
; end
|
;
; Generic pseudo graphics routines for text-only platforms
;
; Written by Stefano Bodrato 07/09/2007
;
;
; Get pixel at (x,y) coordinate.
;
;
; $Id: pointxy.asm,v 1.7 2016-08-05 07:04:09 stefano Exp $
;
INCLUDE "graphics/grafix.inc"
SECTION code_clib
PUBLIC pointxy
EXTERN textpixl
EXTERN __gfx_coords
EXTERN base_graphics
.pointxy
ld a,h
cp maxx
ret nc
ld a,l
cp maxy
ret nc ; y0 out of range
push bc
push de
push hl
ld (__gfx_coords),hl
;push bc
ld c,a
ld b,h
push bc
srl b
srl c
ld hl,(base_graphics)
ld a,c
ld c,b ; !!
and a
jr z,r_zero
ld b,a
ld de,maxx/2
.r_loop
add hl,de
djnz r_loop
.r_zero ; hl = char address
ld e,c
add hl,de
ld a,(hl) ; get current symbol
ld e,a
push hl
ld hl,textpixl
ld e,0
ld b,16
.ckmap cp (hl)
jr z,chfound
inc hl
inc e
djnz ckmap
ld e,0
.chfound ld a,e
pop hl
ex (sp),hl ; save char address <=> restore x,y
ld b,a
ld a,1 ; the bit we want to draw
bit 0,h
jr z,iseven
add a,a ; move right the bit
.iseven
bit 0,l
jr z,evenrow
add a,a
add a,a ; move down the bit
.evenrow
and b
pop bc
pop hl
pop de
pop bc
ret
|
/*
Copyright (c) 2017-2019,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See
the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "gtest/gtest.h"
#include <cstdio>
#include "exeTestHelper.h"
#include "helics/application_api/Endpoints.hpp"
#include "helics/apps/Echo.hpp"
#include "helics/core/BrokerFactory.hpp"
#include <future>
// this test will test basic echo functionality
TEST (echo_tests, echo_test1)
{
helics::FederateInfo fi (helics::core_type::TEST);
fi.coreName = "ecore1";
fi.coreInitString = "-f 2 --autobroker";
helics::apps::Echo echo1 ("echo1", fi);
echo1.addEndpoint ("test");
// fi.logLevel = 4;
helics::MessageFederate mfed ("source", fi);
helics::Endpoint ep1 (&mfed, "src");
auto fut = std::async (std::launch::async, [&echo1]() { echo1.runTo (5.0); });
mfed.enterExecutingMode ();
ep1.send ("test", "hello world");
auto retTime = mfed.requestTime (1.0);
EXPECT_TRUE (ep1.hasMessage ());
EXPECT_LT (retTime, 1.0);
auto m = ep1.getMessage ();
ASSERT_TRUE (m);
EXPECT_EQ (m->data.to_string (), "hello world");
EXPECT_EQ (m->source, "test");
mfed.finalize ();
fut.get ();
}
TEST (echo_tests, echo_test_delay)
{
helics::FederateInfo fi (helics::core_type::TEST);
fi.coreName = "ecore2";
fi.coreInitString = "-f 2 --autobroker";
helics::apps::Echo echo1 ("echo1", fi);
echo1.addEndpoint ("test");
echo1.setEchoDelay (1.2);
helics::MessageFederate mfed ("source", fi);
helics::Endpoint ep1 (&mfed, "src");
auto fut = std::async (std::launch::async, [&echo1]() { echo1.runTo (5.0); });
mfed.enterExecutingMode ();
ep1.send ("test", "hello world");
mfed.requestTime (1.0);
EXPECT_TRUE (!ep1.hasMessage ());
auto ntime = mfed.requestTime (2.0);
EXPECT_EQ (ntime, helics::timeEpsilon + 1.2);
EXPECT_TRUE (ep1.hasMessage ());
auto m = ep1.getMessage ();
ASSERT_TRUE (m);
EXPECT_EQ (m->data.to_string (), "hello world");
EXPECT_EQ (m->source, "test");
mfed.finalize ();
fut.get ();
}
TEST (echo_tests, echo_test_delay_period)
{
helics::FederateInfo fi (helics::core_type::TEST);
fi.coreName = "ecore3";
fi.coreInitString = "-f 2 --autobroker";
fi.setProperty (helics_property_time_period, 1.1);
helics::apps::Echo echo1 ("echo1", fi);
fi.setProperty (helics_property_time_period, 0);
echo1.addEndpoint ("test");
echo1.setEchoDelay (1.2);
helics::MessageFederate mfed ("source", fi);
helics::Endpoint ep1 (&mfed, "src");
auto fut = std::async (std::launch::async, [&echo1]() { echo1.runTo (5.0); });
mfed.enterExecutingMode ();
ep1.send ("test", "hello world");
mfed.requestTime (1.0);
EXPECT_TRUE (!ep1.hasMessage ());
auto ntime = mfed.requestTime (4.0);
EXPECT_EQ (ntime, 2.3);
EXPECT_TRUE (ep1.hasMessage ());
auto m = ep1.getMessage ();
ASSERT_TRUE (m);
EXPECT_EQ (m->data.to_string (), "hello world");
EXPECT_EQ (m->source, "test");
mfed.finalize ();
fut.get ();
}
TEST (echo_tests, echo_test_multiendpoint)
{
helics::FederateInfo fi (helics::core_type::TEST);
fi.coreName = "ecore4";
fi.coreInitString = "-f 2 --autobroker";
helics::apps::Echo echo1 ("echo1", fi);
echo1.addEndpoint ("test");
echo1.addEndpoint ("test2");
echo1.setEchoDelay (1.2);
helics::MessageFederate mfed ("source", fi);
helics::Endpoint ep1 (&mfed, "src");
auto fut = std::async (std::launch::async, [&echo1]() { echo1.runTo (5.0); });
mfed.enterExecutingMode ();
ep1.send ("test", "hello world");
mfed.requestTime (1.0);
ep1.send ("test2", "hello again");
EXPECT_TRUE (!ep1.hasMessage ());
auto ntime = mfed.requestTime (2.0);
EXPECT_EQ (ntime, helics::timeEpsilon + 1.2);
EXPECT_TRUE (ep1.hasMessage ());
auto m = ep1.getMessage ();
ASSERT_TRUE (m);
EXPECT_EQ (m->data.to_string (), "hello world");
EXPECT_EQ (m->source, "test");
ntime = mfed.requestTime (3.0);
EXPECT_EQ (ntime, 2.2);
EXPECT_TRUE (ep1.hasMessage ());
m = ep1.getMessage ();
ASSERT_TRUE (m);
EXPECT_EQ (m->data.to_string (), "hello again");
EXPECT_EQ (m->source, "test2");
mfed.finalize ();
fut.get ();
}
TEST (echo_tests, echo_test_fileload)
{
helics::FederateInfo fi (helics::core_type::TEST);
fi.coreName = "ecore4-file";
fi.coreInitString = "-f 2 --autobroker";
helics::apps::Echo echo1 ("echo1", fi);
echo1.loadFile (std::string (TEST_DIR) + "/echo_example.json");
helics::MessageFederate mfed ("source", fi);
helics::Endpoint ep1 (&mfed, "src");
auto fut = std::async (std::launch::async, [&echo1]() { echo1.runTo (5.0); });
mfed.enterExecutingMode ();
ep1.send ("test", "hello world");
mfed.requestTime (1.0);
ep1.send ("test2", "hello again");
EXPECT_TRUE (!ep1.hasMessage ());
auto ntime = mfed.requestTime (2.0);
EXPECT_EQ (ntime, helics::timeEpsilon + 1.2);
EXPECT_TRUE (ep1.hasMessage ());
auto m = ep1.getMessage ();
ASSERT_TRUE (m);
EXPECT_EQ (m->data.to_string (), "hello world");
EXPECT_EQ (m->source, "test");
ntime = mfed.requestTime (3.0);
EXPECT_EQ (ntime, 2.2);
EXPECT_TRUE (ep1.hasMessage ());
m = ep1.getMessage ();
ASSERT_TRUE (m);
EXPECT_EQ (m->data.to_string (), "hello again");
EXPECT_EQ (m->source, "test2");
mfed.finalize ();
fut.get ();
}
|
; A158004: a(n) = 392*n - 1.
; 391,783,1175,1567,1959,2351,2743,3135,3527,3919,4311,4703,5095,5487,5879,6271,6663,7055,7447,7839,8231,8623,9015,9407,9799,10191,10583,10975,11367,11759,12151,12543,12935,13327,13719,14111,14503,14895,15287,15679,16071,16463,16855,17247,17639,18031,18423,18815,19207,19599,19991,20383,20775,21167,21559,21951,22343,22735,23127,23519,23911,24303,24695,25087,25479,25871,26263,26655,27047,27439,27831,28223,28615,29007,29399,29791,30183,30575,30967,31359,31751,32143,32535,32927,33319,33711,34103,34495,34887,35279,35671,36063,36455,36847,37239,37631,38023,38415,38807,39199,39591,39983,40375,40767,41159,41551,41943,42335,42727,43119,43511,43903,44295,44687,45079,45471,45863,46255,46647,47039,47431,47823,48215,48607,48999,49391,49783,50175,50567,50959,51351,51743,52135,52527,52919,53311,53703,54095,54487,54879,55271,55663,56055,56447,56839,57231,57623,58015,58407,58799,59191,59583,59975,60367,60759,61151,61543,61935,62327,62719,63111,63503,63895,64287,64679,65071,65463,65855,66247,66639,67031,67423,67815,68207,68599,68991,69383,69775,70167,70559,70951,71343,71735,72127,72519,72911,73303,73695,74087,74479,74871,75263,75655,76047,76439,76831,77223,77615,78007,78399,78791,79183,79575,79967,80359,80751,81143,81535,81927,82319,82711,83103,83495,83887,84279,84671,85063,85455,85847,86239,86631,87023,87415,87807,88199,88591,88983,89375,89767,90159,90551,90943,91335,91727,92119,92511,92903,93295,93687,94079,94471,94863,95255,95647,96039,96431,96823,97215,97607,97999
mov $1,$0
mul $1,392
add $1,391
|
; A317301: Sequence obtained by taking the general formula for generalized k-gonal numbers: m*((k - 2)*m - k + 4)/2, where m = 0, +1, -1, +2, -2, +3, -3, ... and k >= 5. Here k = 1.
; 0,1,-2,1,-5,0,-9,-2,-14,-5,-20,-9,-27,-14,-35,-20,-44,-27,-54,-35,-65,-44,-77,-54,-90,-65,-104,-77,-119,-90,-135,-104,-152,-119,-170,-135,-189,-152,-209,-170,-230,-189,-252,-209,-275,-230,-299,-252,-324,-275,-350,-299,-377,-324,-405,-350,-434,-377,-464,-405,-495,-434,-527,-464,-560,-495,-594,-527,-629,-560,-665,-594,-702,-629,-740,-665,-779,-702,-819,-740,-860,-779,-902,-819,-945,-860,-989,-902,-1034,-945,-1080,-989,-1127,-1034,-1175,-1080,-1224,-1127,-1274,-1175,-1325,-1224,-1377,-1274,-1430,-1325,-1484,-1377,-1539,-1430,-1595,-1484,-1652,-1539,-1710,-1595,-1769,-1652,-1829,-1710,-1890,-1769,-1952,-1829,-2015,-1890,-2079,-1952,-2144,-2015,-2210,-2079,-2277,-2144,-2345,-2210,-2414,-2277,-2484,-2345,-2555,-2414,-2627,-2484,-2700,-2555,-2774,-2627,-2849,-2700,-2925,-2774,-3002,-2849,-3080,-2925,-3159,-3002,-3239,-3080,-3320,-3159,-3402,-3239,-3485,-3320,-3569,-3402,-3654,-3485,-3740,-3569,-3827,-3654,-3915,-3740,-4004,-3827,-4094,-3915,-4185,-4004,-4277,-4094,-4370,-4185,-4464,-4277,-4559,-4370,-4655,-4464,-4752,-4559,-4850,-4655,-4949,-4752,-5049,-4850,-5150,-4949,-5252,-5049,-5355,-5150,-5459,-5252,-5564,-5355,-5670,-5459,-5777,-5564,-5885,-5670,-5994,-5777,-6104,-5885,-6215,-5994,-6327,-6104,-6440,-6215,-6554,-6327,-6669,-6440,-6785,-6554,-6902,-6669,-7020,-6785,-7139,-6902,-7259,-7020,-7380,-7139,-7502,-7259,-7625,-7380,-7749,-7502,-7874,-7625
mov $1,$0
mov $2,$0
lpb $2
sub $0,7
sub $2,1
add $1,$2
add $1,$0
sub $2,1
lpe
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r13
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x193bf, %rsi
lea addresses_WT_ht+0x1750d, %rdi
clflush (%rsi)
nop
nop
nop
nop
nop
xor $27465, %r13
mov $67, %rcx
rep movsl
nop
nop
and $7504, %r11
lea addresses_A_ht+0x1daf, %rsi
nop
nop
nop
nop
nop
and $61236, %rbx
movw $0x6162, (%rsi)
nop
nop
nop
nop
sub %rcx, %rcx
lea addresses_D_ht+0x8a7b, %r13
inc %r12
movw $0x6162, (%r13)
add %rbx, %rbx
lea addresses_WC_ht+0xdeaf, %rsi
lea addresses_D_ht+0xcf8f, %rdi
nop
nop
nop
nop
nop
cmp $57805, %rbx
mov $40, %rcx
rep movsq
nop
nop
nop
nop
nop
cmp %r11, %r11
lea addresses_WT_ht+0x1a1af, %rcx
nop
and %rsi, %rsi
movw $0x6162, (%rcx)
nop
nop
nop
nop
xor %r13, %r13
lea addresses_WT_ht+0x12ceb, %r11
nop
nop
nop
cmp $14162, %rdi
and $0xffffffffffffffc0, %r11
vmovntdqa (%r11), %ymm7
vextracti128 $1, %ymm7, %xmm7
vpextrq $0, %xmm7, %r13
nop
and %rcx, %rcx
lea addresses_A_ht+0x1e127, %rsi
lea addresses_UC_ht+0x184af, %rdi
nop
nop
nop
add %r13, %r13
mov $23, %rcx
rep movsq
xor %r12, %r12
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r13
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r13
push %r14
push %r15
push %rbp
push %rdi
// Store
lea addresses_WC+0x8adf, %rbp
nop
nop
nop
nop
and $37017, %rdi
movl $0x51525354, (%rbp)
nop
nop
inc %r14
// Store
lea addresses_WT+0x14d0f, %r15
nop
nop
inc %r13
movw $0x5152, (%r15)
and %r13, %r13
// Faulty Load
lea addresses_normal+0x1daf, %rbp
clflush (%rbp)
nop
nop
add %r10, %r10
movb (%rbp), %r12b
lea oracles, %r14
and $0xff, %r12
shlq $12, %r12
mov (%r14,%r12,1), %r12
pop %rdi
pop %rbp
pop %r15
pop %r14
pop %r13
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WC'}}
{'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 2, 'NT': True, 'type': 'addresses_WT'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_WT_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 2, 'NT': True, 'type': 'addresses_WT_ht'}}
{'src': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 32, 'NT': True, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_UC_ht'}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iot1click-projects/model/DeletePlacementResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::IoT1ClickProjects::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DeletePlacementResult::DeletePlacementResult()
{
}
DeletePlacementResult::DeletePlacementResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DeletePlacementResult& DeletePlacementResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
AWS_UNREFERENCED_PARAM(result);
return *this;
}
|
/*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*
* Copyright (C) 1990,91 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.1.1.1 $
|
| Classes:
| SbLine
|
| Author(s) : Nick Thompson, Howard Look
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#include <Inventor/SbBox.h>
#include <Inventor/SbLinear.h>
//////////////////////////////////////////////////////////////////////////////
//
// Line class
//
//////////////////////////////////////////////////////////////////////////////
// construct a line given 2 points on the line
SbLine::SbLine(const SbVec3f &p0, const SbVec3f &p1)
{
setValue(p0, p1);
}
// setValue constructs a line give two points on the line
void
SbLine::setValue(const SbVec3f &p0, const SbVec3f &p1)
{
pos = p0;
dir = p1 - p0;
dir.normalize();
}
// find points on this line and on line2 that are closest to each other.
// If the lines intersect, then ptOnThis and ptOnLine2 will be equal.
// If the lines are parallel, then FALSE is returned, and the contents of
// ptOnThis and ptOnLine2 are undefined.
SbBool
SbLine::getClosestPoints( const SbLine &line2,
SbVec3f &ptOnThis,
SbVec3f &ptOnLine2 ) const
{
float s, t, A, B, C, D, E, F, denom;
SbVec3f pos2 = line2.getPosition();
SbVec3f dir2 = line2.getDirection();
// DERIVATION:
// [1] parametric descriptions of desired pts
// pos + s * dir = ptOnThis
// pos2 + t * dir2 = ptOnLine2
// [2] (By some theorem or other--)
// If these are closest points between lines, then line connecting
// these points is perpendicular to both this line and line2.
// dir . ( ptOnLine2 - ptOnThis ) = 0
// dir2 . ( ptOnLine2 - ptOnThis ) = 0
// OR...
// dir . ( pos2 + t * dir2 - pos - s * dir ) = 0
// dir2 . ( pos2 + t * dir2 - pos - s * dir ) = 0
// [3] Rearrange the terms:
// t * [ dir . dir2 ] - s * [dir . dir ] = dir . pos - dir . pos2
// t * [ dir2 . dir2 ] - s * [dir2 . dir ] = dir2 . pos - dir2 . pos2
// [4] Let:
// A= dir . dir2
// B= dir . dir
// C= dir . pos - dir . pos2
// D= dir2 . dir2
// E= dir2 . dir
// F= dir2 . pos - dir2 . pos2
// So [3] above turns into:
// t * A - s * B = C
// t * D - s * E = F
// [5] Solving for s gives:
// s = (CD - AF) / (AE - BD)
// [6] Solving for t gives:
// t = (CE - BF) / (AE - BD)
A = dir.dot( dir2 );
B = dir.dot( dir );
C = dir.dot( pos ) - dir.dot( pos2 );
D = dir2.dot( dir2 );
E = dir2.dot( dir );
F = dir2.dot( pos ) - dir2.dot( pos2 );
denom = A * E - B * D;
if ( denom == 0.0) // the two lines are parallel
return FALSE;
s = ( C * D - A * F ) / denom;
t = ( C * E - B * F ) / denom;
ptOnThis = pos + dir * s;
ptOnLine2 = pos2 + dir2 * t;
return TRUE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Returns the closes point on this line to the given point.
//
// Use: public
SbVec3f
SbLine::getClosestPoint(const SbVec3f &point) const
//
////////////////////////////////////////////////////////////////////////
{
// vector from origin of this line to given point
SbVec3f p = point - pos;
// find the length of p when projected onto this line
// (which has direction d)
// length = |p| * cos(angle b/w p and d) = (p.d)/|d|
// but |d| = 1, so
float length = p.dot(dir);
// vector coincident with this line
SbVec3f proj = dir;
proj *= length;
SbVec3f result = pos + proj;
return result;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Intersect the line with a 3D box. The line is intersected with the
// twelve triangles that make up the box.
//
// Use: internal
SbBool
SbLine::intersect(const SbBox3f &box, SbVec3f &enter, SbVec3f &exit) const
//
////////////////////////////////////////////////////////////////////////
{
if (box.isEmpty())
return FALSE;
const SbVec3f &pos = getPosition(), &dir = getDirection();
const SbVec3f &max = box.getMax(), &min = box.getMin();
SbVec3f points[8], inter, bary;
SbPlane plane;
int i, v0, v1, v2;
SbBool front = FALSE, valid, validIntersection = FALSE;
//
// First, check the distance from the ray to the center
// of the box. If that distance is greater than 1/2
// the diagonal distance, there is no intersection
// diff is the vector from the closest point on the ray to the center
// dist2 is the square of the distance from the ray to the center
// radi2 is the square of 1/2 the diagonal length of the bounding box
//
float t = (box.getCenter() - pos).dot(dir);
SbVec3f diff(pos + t * dir - box.getCenter());
float dist2 = diff.dot(diff);
float radi2 = (max - min).dot(max - min) * 0.25f;
if (dist2 > radi2)
return FALSE;
// set up the eight coords of the corners of the box
for(i = 0; i < 8; i++)
points[i].setValue(i & 01 ? min[0] : max[0],
i & 02 ? min[1] : max[1],
i & 04 ? min[2] : max[2]);
// intersect the 12 triangles.
for(i = 0; i < 12; i++) {
switch(i) {
case 0: v0 = 2; v1 = 1; v2 = 0; break; // +z
case 1: v0 = 2; v1 = 3; v2 = 1; break;
case 2: v0 = 4; v1 = 5; v2 = 6; break; // -z
case 3: v0 = 6; v1 = 5; v2 = 7; break;
case 4: v0 = 0; v1 = 6; v2 = 2; break; // -x
case 5: v0 = 0; v1 = 4; v2 = 6; break;
case 6: v0 = 1; v1 = 3; v2 = 7; break; // +x
case 7: v0 = 1; v1 = 7; v2 = 5; break;
case 8: v0 = 1; v1 = 4; v2 = 0; break; // -y
case 9: v0 = 1; v1 = 5; v2 = 4; break;
case 10: v0 = 2; v1 = 7; v2 = 3; break; // +y
case 11: v0 = 2; v1 = 6; v2 = 7; break;
}
if ((valid = intersect(points[v0], points[v1], points[v2],
inter, bary, front)) == TRUE) {
if (front) {
enter = inter;
validIntersection = valid;
}
else {
exit = inter;
validIntersection = valid;
}
}
}
return validIntersection;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Intersect the line with a 3D box. The line is augmented with an
// angle to form a cone. The box must lie within pickAngle of the
// line. If the angle is < 0.0, abs(angle) is the radius of a
// cylinder for an orthographic intersection.
//
// Use: internal
SbBool
SbLine::intersect(float angle, const SbBox3f &box) const
//
////////////////////////////////////////////////////////////////////////
{
if (box.isEmpty())
return FALSE;
const SbVec3f &max = box.getMax(), &min = box.getMin();
float fuzz = 0.0;
int i;
if (angle < 0.0)
fuzz = - angle;
else {
// Find the farthest point on the bounding box (where the pick
// cone will be largest). The amount of fuzz at this point will
// be the minimum we can use. Expand the box by that amount and
// do an intersection.
double tanA = tan(angle);
for(i = 0; i < 8; i++) {
SbVec3f point(i & 01 ? min[0] : max[0],
i & 02 ? min[1] : max[1],
i & 04 ? min[2] : max[2]);
// how far is point from line origin??
SbVec3f diff(point - getPosition());
double thisFuzz = sqrt(diff.dot(diff)) * tanA;
if (thisFuzz > fuzz)
fuzz = float(thisFuzz);
}
}
SbBox3f fuzzBox = box;
fuzzBox.extendBy(SbVec3f(min[0] - fuzz, min[1] - fuzz, min[2] - fuzz));
fuzzBox.extendBy(SbVec3f(max[0] + fuzz, max[1] + fuzz, max[2] + fuzz));
SbVec3f scratch1, scratch2;
return intersect(fuzzBox, scratch1, scratch2);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Intersect the line with a point. The line is augmented with an
// angle to form a cone. The point must lie within pickAngle of the
// line. If the angle is < 0.0, abs(angle) is
// the radius of a cylinder for an orthographic intersection.
//
// Use: internal
SbBool
SbLine::intersect(
float pickAngle, // The angle which makes the cone
const SbVec3f &point) const // The point to interesect.
//
////////////////////////////////////////////////////////////////////////
{
float t, d;
// how far is point from line origin??
SbVec3f diff(point - getPosition());
t = diff.dot(getDirection());
if(t > 0) {
d = float(sqrt(diff.dot(diff)) - t*t);
if (pickAngle < 0.0)
return (d < -pickAngle);
return ((d/t) < pickAngle);
}
return FALSE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Intersect the line with a line segment. The line is augmented with
// an angle to form a cone. The line segment must lie within pickAngle
// of the line. If an intersection occurs, the intersection point is
// placed in intersection.
//
// Use: internal
SbBool
SbLine::intersect(
float pickAngle, // The angle which makes the cone
const SbVec3f &v0, // One endpoint of the line segment
const SbVec3f &v1, // The other endpoint of the line segment
SbVec3f &intersection) const // The intersection point
//
////////////////////////////////////////////////////////////////////////
{
SbVec3f ptOnLine;
SbLine inputLine(v0, v1);
float distance;
SbBool validIntersection = FALSE;
if(getClosestPoints(inputLine, ptOnLine, intersection)) {
// check to make sure the intersection is within the line segment
if((intersection - v0).dot(v1 - v0) < 0)
intersection = v0;
else if((intersection - v1).dot(v0 - v1) < 0)
intersection = v1;
distance = (ptOnLine - intersection).length();
if (pickAngle < 0.0)
return (distance < -pickAngle);
validIntersection = ((distance / (ptOnLine - getPosition()).length())
< pickAngle);
}
return validIntersection;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Intersects the line with the triangle formed bu v0, v1, v2.
// Returns TRUE if there is an intersection. If there is an
// intersection, barycentric will contain the barycentric
// coordinates of the intersection (for v0, v1, v2, respectively)
// and front will be set to TRUE if the ray intersected the front
// of the triangle (as defined by the right hand rule).
//
// Use: internal
SbBool
SbLine::intersect(const SbVec3f &v0, const SbVec3f &v1, const SbVec3f &v2,
SbVec3f &intersection,
SbVec3f &barycentric, SbBool &front) const
//
////////////////////////////////////////////////////////////////////////
{
//////////////////////////////////////////////////////////////////
//
// The method used here is described by Didier Badouel in Graphics
// Gems (I), pages 390 - 393.
//
//////////////////////////////////////////////////////////////////
#define EPSILON 1e-10
//
// (1) Compute the plane containing the triangle
//
SbVec3f v01 = v1 - v0;
SbVec3f v12 = v2 - v1;
SbVec3f norm = v12.cross(v01); // Un-normalized normal
// Normalize normal to unit length, and make sure the length is
// not 0 (indicating a zero-area triangle)
if (norm.normalize() < EPSILON)
return FALSE;
//
// (2) Compute the distance t to the plane along the line
//
float d = getDirection().dot(norm);
if (d < EPSILON && d > -EPSILON)
return FALSE; // Line is parallel to plane
float t = norm.dot(v0 - getPosition()) / d;
// Note: we DO NOT ignore intersections behind the eye (t < 0.0)
//
// (3) Find the largest component of the plane normal. The other
// two dimensions are the axes of the aligned plane we will
// use to project the triangle.
//
float xAbs = norm[0] < 0.0 ? -norm[0] : norm[0];
float yAbs = norm[1] < 0.0 ? -norm[1] : norm[1];
float zAbs = norm[2] < 0.0 ? -norm[2] : norm[2];
int axis0, axis1;
if (xAbs > yAbs && xAbs > zAbs) {
axis0 = 1;
axis1 = 2;
}
else if (yAbs > zAbs) {
axis0 = 2;
axis1 = 0;
}
else {
axis0 = 0;
axis1 = 1;
}
//
// (4) Determine if the projected intersection (of the line and
// the triangle's plane) lies within the projected triangle.
// Since we deal with only 2 components, we can avoid the
// third computation.
//
float intersection0 = getPosition()[axis0] + t * getDirection()[axis0];
float intersection1 = getPosition()[axis1] + t * getDirection()[axis1];
SbVec2f diff0, diff1, diff2;
SbBool isInter = FALSE;
float alpha, beta;
diff0[0] = intersection0 - v0[axis0];
diff0[1] = intersection1 - v0[axis1];
diff1[0] = v1[axis0] - v0[axis0];
diff1[1] = v1[axis1] - v0[axis1];
diff2[0] = v2[axis0] - v0[axis0];
diff2[1] = v2[axis1] - v0[axis1];
// Note: This code was rearranged somewhat from the code in
// Graphics Gems to provide a little more numeric
// stability. However, it can still miss some valid intersections
// on very tiny triangles.
isInter = FALSE;
beta = ((diff0[1] * diff1[0] - diff0[0] * diff1[1]) /
(diff2[1] * diff1[0] - diff2[0] * diff1[1]));
if (beta >= 0.0 && beta <= 1.0) {
alpha = -1.0;
if (diff1[1] < -EPSILON || diff1[1] > EPSILON)
alpha = (diff0[1] - beta * diff2[1]) / diff1[1];
else
alpha = (diff0[0] - beta * diff2[0]) / diff1[0];
isInter = (alpha >= 0.0 && alpha + beta <= 1.0);
}
//
// (5) If there is an intersection, set up the barycentric
// coordinates and figure out if the front was hit.
//
if (isInter) {
barycentric.setValue(1.0f - (alpha + beta), alpha, beta);
front = (getDirection().dot(norm) < 0.0);
intersection = getPosition() + t * getDirection();
}
return isInter;
#undef EPSILON
}
|
;*****************************************************************************
;*++
;* Name : $RCSfile: fast.asm,v $
;* Title :
;* ASM Author : Jim Page
;* Created : 20/04/94
;*
;* Copyright : 1995-2022 Imagination Technologies (c)
;* License : MIT
;*
;* Description : Pentium optimised shading routines
;*
;* Program Type: ASM module (.dll)
;*
;* RCS info:
;*
;* $Date: 1997/04/14 16:04:46 $
;* $Revision: 1.2 $
;* $Locker: $
;* $Log: fast.asm,v $
;; Revision 1.2 1997/04/14 16:04:46 mjg
;; Fixed the declaration of 'Int3'.
;;
;; Revision 1.1 1997/04/03 14:03:44 jop
;; Initial revision
;;
;; Revision 1.3 1997/02/05 13:48:59 ncj
;; Added CPUID instruction
;;
;; Revision 1.2 1996/08/02 18:03:09 jop
;; Added FPU restore
;;
;; Revision 1.1 1996/06/10 11:51:12 jop
;; Initial revision
;;
;; Revision 1.1 1996/06/10 11:39:13 jop
;; Initial revision
;;
;; Revision 1.2 1996/02/07 15:17:09 ncj
;; Added int3() utility
;;
;; Revision 1.1 1995/10/20 10:32:51 jop
;; Initial revision
;;
;*
;*--
;*****************************************************************************
.386
_DATA SEGMENT DWORD USE32 PUBLIC 'DATA'
wFPUFlags dw ?
wFPUSaveFlags dw ?
_DATA ENDS
_TEXT SEGMENT DWORD USE32 PUBLIC 'CODE'
ASSUME CS:FLAT, DS:FLAT, ES:FLAT, SS:NOTHING, FS:NOTHING, GS:NOTHING
PUBLIC _SetupFPU
PUBLIC _RestoreFPU
PUBLIC _GetCS
PUBLIC _GetDS
PUBLIC _Int3
PUBLIC _cpuid
_GetDS PROC
mov ax, ds
ret
_GetDS ENDP
_GetCS PROC
mov ax, cs
ret
_GetCS ENDP
_SetupFPU PROC
fstcw [wFPUSaveFlags]
mov ax, [wFPUSaveFlags]
and ax, 0FCFFh
or ax, 00C00h
mov [wFPUFlags], ax
fldcw [wFPUFlags]
ret
_SetupFPU ENDP
_RestoreFPU PROC
fldcw [wFPUSaveFlags]
ret
_RestoreFPU ENDP
_Int3 PROC
int 3
ret
_Int3 ENDP
_cpuid PROC
db 0Fh ; CPUID instruction
db 0A2h
ret
_cpuid ENDP
_TEXT ENDS
END
; end of file $RCSfile: fast.asm,v $
|
const_def
const PAL_TOWNMAP_BORDER ; 0
const PAL_TOWNMAP_EARTH ; 1
const PAL_TOWNMAP_MOUNTAIN ; 2
const PAL_TOWNMAP_CITY ; 3
const PAL_TOWNMAP_POI ; 4
const PAL_TOWNMAP_POI_MTN ; 5
townmappals: MACRO
rept _NARG / 2
dn PAL_TOWNMAP_\2, PAL_TOWNMAP_\1
shift 2
endr
ENDM
; gfx/pokegear/town_map.png
townmappals EARTH, EARTH, EARTH, MOUNTAIN, MOUNTAIN, MOUNTAIN, BORDER, BORDER
townmappals EARTH, EARTH, CITY, EARTH, POI, POI_MTN, POI, POI_MTN
townmappals EARTH, EARTH, EARTH, MOUNTAIN, MOUNTAIN, MOUNTAIN, BORDER, BORDER
townmappals EARTH, EARTH, BORDER, EARTH, EARTH, BORDER, BORDER, BORDER
townmappals EARTH, EARTH, EARTH, MOUNTAIN, MOUNTAIN, MOUNTAIN, BORDER, BORDER
townmappals BORDER, BORDER, BORDER, BORDER, BORDER, BORDER, BORDER, BORDER
; gfx/pokegear/pokegear.png
townmappals BORDER, BORDER, BORDER, BORDER, POI, POI, POI, BORDER
townmappals BORDER, BORDER, BORDER, BORDER, BORDER, BORDER, BORDER, BORDER
townmappals CITY, CITY, CITY, CITY, CITY, CITY, CITY, CITY
townmappals CITY, CITY, CITY, CITY, CITY, CITY, CITY, BORDER
townmappals CITY, CITY, CITY, CITY, CITY, CITY, CITY, CITY
townmappals BORDER, BORDER, BORDER, BORDER, BORDER, BORDER, BORDER, BORDER
|
/*
* Copyright 2019 Autoware Foundation. All rights reserved.
*
* 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.
*/
#include <lane_change_planner/lane_changer.h>
#include <rclcpp/rclcpp.hpp>
int main(int argc, char ** argv)
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<lane_change_planner::LaneChanger>());
rclcpp::shutdown();
return 0;
}
|
.program:
ji i4
noop
DATA_SECTION_OFFSET[0..32]
DATA_SECTION_OFFSET[32..64]
lw $ds $is 1
add $$ds $$ds $is
lw $r0 data_0 ; literal instantiation
lw $r1 data_0 ; literal instantiation
lw $r0 data_0 ; literal instantiation
jnzi $r0 i11
ji i12
lw $r1 data_1 ; literal instantiation
move $r0 $r1
jnzi $r1 i15
lw $r1 data_1 ; literal instantiation
ret $r1
noop ; word-alignment of data section
.data:
data_0 .bool 0x00
data_1 .bool 0x01
|
LoreleisRoom_h:
db GYM ; tileset
db LORELEIS_ROOM_HEIGHT, LORELEIS_ROOM_WIDTH ; dimensions (y, x)
dw LoreleisRoom_Blocks ; blocks
dw LoreleisRoom_TextPointers ; texts
dw LoreleisRoom_Script ; scripts
db 0 ; connections
dw LoreleisRoom_Object ; objects
|
/**************************************************************************
* Created: 2010/06/07 2:09
* Author: Eugene V. Palchukovsky
* E-mail: eugene@palchukovsky.com
* -------------------------------------------------------------------
* Project: TunnelEx
* URL: http://tunnelex.net
**************************************************************************/
#include "Prec.h"
#include "UdpConnection.hpp"
#include "Modules/Inet/InetEndpointAddress.hpp"
using namespace TunnelEx;
using namespace TunnelEx::Mods;
using namespace TunnelEx::Mods::Upnp;
UdpConnection::UdpConnection(
unsigned short externalPort,
const Inet::UdpEndpointAddress &address,
const RuleEndpoint &ruleEndpoint,
SharedPtr<const EndpointAddress> ruleEndpointAddress)
: Base(address, ruleEndpoint, ruleEndpointAddress) {
const AutoPtr<EndpointAddress> openedAddress = Base::GetLocalAddress();
ServiceRule::Service service;
service.uuid = Helpers::Uuid().GetAsString().c_str();
service.name = L"Upnpc";
service.param = UpnpcService::CreateParam(
Client::PROTO_UDP,
externalPort,
boost::polymorphic_downcast<Inet::InetEndpointAddress *>(
openedAddress.Get())->GetHostName(),
boost::polymorphic_downcast<Inet::InetEndpointAddress *>(
openedAddress.Get())->GetPort(),
true, // @todo: see TEX-610
false);
SharedPtr<ServiceRule> rule(new ServiceRule);
// WString ruleUuid = rule->GetUuid();
rule->GetServices().Append(service);
//! @todo: see TEX-611 [2010/06/07 1:39]
/* m_server.UpdateRule(rule);
ruleUuid.Swap(m_upnpRuleUuid); */
m_upnpcService.reset(new UpnpcService(rule, rule->GetServices()[0]));
m_upnpcService->Start();
}
UdpConnection::~UdpConnection() throw() {
//...//
}
|
; Yahtzee 2600
; ============
;
; A port of Yahtzee to the Atari 2600
;
; © 2019 Jeremy J Starcher
; < jeremy.starcher@gmail.com >
;
; The skeleton of this code is ripped from the
; Atari version of 2048 by...
;
; © 2014 Carlos Duarte do Nascimento (chesterbr)
; <cd@pobox.com | @chesterbr | http://chester.me>
;
; Latest version, contributors and general info:
; http://github.com/chesterbr/2048-2060
;
; Building
; ---------
;
; Building requires DASM (http://dasm-dillon.sourceforge.net/)
; and node.js
;
; You'll want to use the `build.sh` script (Unix only)
; Timings
; -------
;
; Since the shift routine can have unpredictable timing (and I wanted some
; freedom to move routines between overscan and vertical blank), I decided
; to use RIOT timers instead of the traditional scanline count. It is not
; the usual route for games (as they tend to squeeze every scanline of
; processing), but for this project it worked fine.
;
; [1] http://skilldrick.github.io/easy6502/
; [2] http://www.slideshare.net/chesterbr/atari-2600programming
PROCESSOR 6502
INCLUDE "vcs.h"
INCLUDE "macros.h"
;===============================================================================
; Define RAM Usage
;===============================================================================
; define a segment for variables
; .U means uninitialized, does not end up in ROM
SEG.U VARS
; RAM starts at $80
ORG $80
INCLUDE "ram.asm";
.preScoreRamTop:
INCLUDE "build/score_ram.asm";
.postScoreRamTop:
;========================================j=======================================
; free space check before End of Cartridge
;===============================================================================
if (* & $FF)
echo "......", [.postScoreRamTop - .preScoreRamTop]d, "bytes RAM used by scores."
echo "......", [.preScoreRamTop - .startOfRam]d, "bytes RAM used by other."
echo "######", [$FF - *]d, "bytes free before end of RAM."
echo "######", [127 - [$FF - *]]d, "Total bytes of RAM used."
endif
;===============================================================================
; Start ROM
;===============================================================================
SEG CODE
ORG $F000
startofrom: ds 0
INCLUDE "build/digits_bitmap.asm"
INCLUDE "build/score_bitmap.asm";
; Order: NTSC, PAL. (thanks @SvOlli)
VBlankTime64T:
.byte 44,74
OverscanTime64T:
.byte 35,65
;===============================================================================
; free space check on this page
;===============================================================================
if (* & $FF)
echo "------", [* - startofrom]d, "bytes of graphics.asm. ", [startofrom - * + 256]d, "bytes wasted."
endif
; We ran out of room with graphics.asm.
; start a new page.
align 256
page2start: = *
include "build/faces.asm"
include "build/score_lookup.asm"
include "build/labels_bitmap.asm"
include "constants.asm"
;;;;;;;;;;;;;;;
;; BOOTSTRAP ;;
;;;;;;;;;;;;;;;
Initialize: subroutine ; Cleanup routine from macro.h (by Andrew Davie/DASM)
sei
cld
ldx #0
txa
tay
.CleanStack:
dex
txs
pha
bne .CleanStack
;;;;;;;;;;;;;;;
;; TIA SETUP ;;
;;;;;;;;;;;;;;;
lda #%00000001 ; Playfield (grid) in mirror (symmetrical) mode
sta CTRLPF
;;;;;;;;;;;;;;;;;;;
;; PROGRAM SETUP ;;
;;;;;;;;;;;;;;;;;;;
subroutine
lda #0
sta OffsetIntoScoreList ; Reset te top line
lda #$4c
sta Rand8 ; Seed
;;;;;;;;;;;;;;;;;
;; FRAME START ;;
;;;;;;;;;;;;;;;;;
StartFrame: subroutine
lda #%00000010 ; VSYNC
sta VSYNC
REPEAT 3
sta WSYNC
REPEND
lda #0
sta VSYNC
sta WSYNC
ldx #$00
lda #ColSwitchMask ; VBLANK start
bit SWCHB
bne .NoVBlankPALAdjust ; "Color" => NTSC; "B•W" = PAL
inx ; (this adjust will appear a few times in the code)
.NoVBlankPALAdjust:
lda VBlankTime64T,x
sta TIM64T ; Use a RIOT timer (with the proper value) instead
lda #0 ; of counting scanlines (since we only care about
sta VBLANK ; the overall time)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OTHER FRAME CONFIGURATION ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
inc BlinkClock ; Increment our timer
lda BlinkClock ; Load into into register "A"
cmp #BlinkRate ; Compare to the max value
bne .noToggleBlink ; Not equal? Skip ahead
lda StatusBits ; Otherwise get the current phase
eor #StatusBlinkOn ; XOR the bit -- toggle
sta StatusBits ; Save the new phase
lda #0 ; Load the new timer value
sta BlinkClock ; And save it
.noToggleBlink
jsr CalcBlinkMask
jsr random
lda #StatusPlayHand
and StatusBits
beq .noplay
clearBit StatusPlayHand, StatusBits
lda #ScorePhaseCalcUpper
sta ScorePhase
ldy OffsetIntoScoreList ; The address
lda score_low,y ; Slow already filled?
cmp #Unscored
bne .noplay ; Don't play again
lda CalcScoreslookupLow,y
sta GraphicBmpPtr + 0
lda CalcScoreslookupHigh,y
sta GraphicBmpPtr + 1
jmp (GraphicBmpPtr)
AfterCalc:
ldy OffsetIntoScoreList ; The address
lda #$AA
sta score_high,y
lda ScoreAcc
sta score_low,y
jsr StartNewRound
.noplay
jsr CalcSubtotals
; Pre-fill the graphic pointers' MSBs, so we only have to
; figure out the LSBs for each tile or digit
lda #>Digits ; MSB of tiles/digits page
ldx #11 ; 12-byte table (6 digits), zero-based
.FillMsbLoop1:
sta GraphicBmpPtr,x
dex ; Skip to the next MSB
dex
bpl .FillMsbLoop1
;;;;;;;;;;;;;;;;;;;;;;;;;
;; REMAINDER OF VBLANK ;;
;;;;;;;;;;;;;;;;;;;;;;;;;
subroutine
.WaitForVBlankEndLoop:
lda INTIM ; Wait until the timer signals the actual end
bne .WaitForVBlankEndLoop ; of the VBLANK period
sta WSYNC
;;;;;;;;;;;;;;;;;
;; SCORE SETUP ;;
;;;;;;;;;;;;;;;;;
ScoreSetup:
; general configuration
lda #ScoreLinesPerPage
sta ScoreLineCounter
lda #[0 - TopPadding]
sta ScreenLineIndex
lda GameState
cmp #TitleScreen
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Start showing each scoreline in a loop ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
YesScore: subroutine
lda #0 ; No players until we start
sta GRP0
sta GRP1
; What color to make this particular score line?
ldx #ScoreColor
lda ActiveArea
cmp #ActiveAreaScores
bne .UseInactiveColor
lda ScoreLineCounter
cmp ActiveScoreLine
beq .UsePrimaryColor
.UseInactiveColor
ldx #InactiveScoreColor
.UsePrimaryColor:
stx ActiveScoreLineColor
; Copy the score to the scratch buffer
clc
lda ScreenLineIndex
adc OffsetIntoScoreList
tax
sta ScoreLineIndex
lda score_low,x
sta ScoreBCD+2
lda score_high,x
sta ScoreBCD+1
sta WSYNC
; Score setup scanlines 2-3:
; player graphics triplicated and positioned like this: P0 P1 P0 P1 P0 P1
; also, set their colors
lda #PlayerThreeCopies ; (2)
sta NUSIZ0 ; (3)
sta NUSIZ1 ; (3)
lda #VerticalDelay ; (2) ; Needed for precise timing of GRP0/GRP1
sta VDELP0 ; (3)
sta VDELP1 ; (3)
REPEAT 10 ; (20=10x2) ; Delay to position right
nop
REPEND
sta RESP0 ; (3) ; Position P0
sta RESP1 ; (3) ; Position P1
sta WSYNC
lda #$E0 ; Fine-tune player positions to center on screen
sta HMP0
lda #$F0
sta HMP1
sta WSYNC
sta HMOVE ; (3)
ldx ActiveScoreLineColor
stx COLUP0
stx COLUP1
; Score setup scanlines 4-5
; set the graphic pointers for each score digit
ldy #2 ; (2) ; Score byte counter (source)
ldx #10 ; (2) ; Graphic pointer counter (target)
clc ; (2)
.loop:
lda ScoreBCD,y ; (4)
and #$0F ; (2) ; Lower nibble
sta TempVar1 ; (3)
asl ; (2) ; A = digit x 2
asl ; (2) ; A = digit x 4
adc TempVar1 ; (3) ; 4.digit + digit = 5.digit
adc #<Digits ; (2) ; take from the first digit
sta GraphicBmpPtr,x ; (4) ; Store lower nibble graphic
dex ; (2)
dex ; (2)
lda ScoreBCD,y ; (4)
and #$F0 ; (2)
lsr ; (2)
lsr ; (2)
lsr ; (2)
lsr ; (2)
sta TempVar1 ; (3) ; Higher nibble
asl ; (2) ; A = digit x 2
asl ; (2) ; A = digit x 4
adc TempVar1 ; (3) ; 4.digit + digit = 5.digit
adc #<Digits ; (2) ; take from the first digit
sta GraphicBmpPtr,x ; (4) ; store higher nibble graphic
dex ; (2)
dex ; (2)
dey ; (2)
bpl .loop ; (2*)
sta WSYNC ; ; We take less than 2 scanlines, round up
;;;;;;;;;;;
;; SCORE ;;
;;;;;;;;;;;
subroutine
ldy #4 ; 5 scanlines
sty ScanLineCounter
; Check if the line we are drawing is part of the scorecard
; or part of the top/bottom filler
lda ScoreLineIndex
tax
adc #TopPadding ; Move into the a good compare range
bcs .StartBlankLineFiller
cmp #MaxScoreLines
bcs .StartBlankLineFiller
jmp ShowRealScoreLine
.StartBlankLineFiller:
; There is nothing to show for this position, but
; we need to still show some data
LDY #6
.loop:
sta WSYNC
lda #%00000001 ; Reflect bit
sta CTRLPF ; Set it
; lda #$96 ; Color
; sta COLUBK ; Set playfield color
DEY
bne .loop
lda #BackgroundColor
sta COLUBK ; Set playfield color
jmp ScoreCleanup
ShowRealScoreLine: subroutine
; Point the symbol map at the current label to draw
lda scoreglyph0lsb,x
sta GraphicBmpPtr+0
lda #>scoreglyphs0
sta GraphicBmpPtr+1
lda scoreglyph1lsb,x
sta GraphicBmpPtr+2
lda #>scoreglyphs1
sta GraphicBmpPtr+3
;; This loop is so tight there isn't room for *any* additional calculations.
;; So we have to calculate DrawSymbolsMap *before* we hit this code.
.loop:
ldy ScanLineCounter ; 6-digit loop is heavily inspired on Berzerk's
lda (GraphicBmpPtr+0),y
sta GRP0
sta WSYNC
lda (GraphicBmpPtr+2),y
sta GRP1
lda (GraphicBmpPtr+4),y
sta GRP0
lda (GraphicBmpPtr+6),y
sta TempDigitBmp
lda (GraphicBmpPtr+8),y
tax
lda (GraphicBmpPtr+10),y
tay
lda TempDigitBmp
sta GRP1
stx GRP0
sty GRP1
sta GRP0
dec ScanLineCounter
bpl .loop
ScoreCleanup: ; 1 scanline
lda #0
sta VDELP0
sta VDELP1
sta GRP0
sta GRP1
sta WSYNC
LoopScore
inc ScreenLineIndex
dec ScoreLineCounter
beq FrameBottomSpace
jmp YesScore
FrameBottomSpace: subroutine
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; BOTTOM SPACE BELOW GRID ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
sta WSYNC
lda #DieFaceColor ; Color
sta COLUPF ; Set playfield color
lda #%00000001 ; Reflect bit
sta CTRLPF ; Set it
lda #AccentColor
sta COLUP0
sta COLUP1
sta HMCLR
lda #1 ; Delay until the next scan line = TRUE
sta VDELP0 ; Player 0
lda #19 ; Position
ldx #0 ; GRP0
jsr PosObject
lda #PlayerThreeCopies
sta NUSIZ0
lda #%1100000 ; The pattern
sta GRP0
lda #46 ; Position
ldx #1 ; GRP0
jsr PosObject
lda #PlayerThreeCopies
sta NUSIZ1
lda #%00000011 ; The pattern
sta GRP1
sta WSYNC
sta HMOVE
DiceRowScanLines = 4
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Calculate the dice PF fields and put them in shadow registers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; lda #%00010000
; sta RerollDiceMask
MAC merge
;; {1} - The face offset
;; {2} - Which line of the dice
;; {3} - which shadow register
ldx [RolledDice + {1}] ; The value of the face
; lda #StatusBlinkOn
; bit StatusBits
; bne .dontmaskface
lda #[1 << {1}] ; Calculate the bitmask position
bit RerollDiceMask ; Compare against the mask
beq .dontmaskface ; masked? Keep it
ldx #MaskedDieFace
.dontmaskface:
lda {3} ; Load the shadow register
ora faceL{2}P{1},x ; merge in the face bitmap
sta {3} ; And re-save
ENDM
MAC showLineForAllFaces
lda #0
sta SPF0
sta SPF1
sta SPF2
merge 0, {1}, SPF0
merge 1, {1}, SPF1
merge 2, {1}, SPF1
merge 3, {1}, SPF2
merge 4, {1}, SPF2
jsr showDice
ENDM
showLineForAllFaces 0
showLineForAllFaces 1
showLineForAllFaces 2
; Let the sprites extend a little more
sta WSYNC
sta WSYNC
sta WSYNC
sta WSYNC
lda #0
sta GRP0
sta GRP1
sta WSYNC
lda ActiveArea
cmp #ActiveAreaReRoll
bne .noChangeRerollColor
ldx #ScoreColor
stx COLUP0
stx COLUP1
.noChangeRerollColor
lda RollCount
sta PrintLabelID
jsr PrintLabel
; 262 scan lines total
ldx #20 + 1 - (DiceRowScanLines * 3)
.loop:
sta WSYNC
dex
bne .loop
;;;;;;;;;;;;;;
;; OVERSCAN ;;
;;;;;;;;;;;;;;
subroutine
lda #0 ; Clear pattern
sta PF0
sta PF1
sta PF2
lda #%01000010 ; Disable output
sta VBLANK
ldx #$00
lda #ColSwitchMask
bit SWCHB
bne .NoOverscanPALAdjust
inx
.NoOverscanPALAdjust:
lda OverscanTime64T,x ; Use a timer adjusted to the color system's TV
sta TIM64T ; timings to end Overscan, same as VBLANK
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SELECT, RESET AND P0 FIRE BUTTON ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
subroutine
ldx GameMode ; Remember if we were on one or two player mode
lda SWCHB ; We only want the switch presses once
and #SelectResetMask ; (in particular GAME SELECT)
cmp LastSWCHB
beq .NoSwitchChange
sta LastSWCHB ; Store so we know if it's a repeat next time
cmp #GameSelect ; GAME SELECT flips single/multiplayer...
bne .NoSelect
lda GameMode
eor #1
sta GameMode
jmp StartNewGame ; ...and restarts with no further game mode change
.NoSelect:
cmp #GameReset ; GAME RESET restarts the game at any time
beq .Restart
.NoSwitchChange:
lda INPT4
bpl .ButtonPressed ; P0 Fire button pressed?
clearBit StatusFireDown, StatusBits
jmp .NoRestart
.ButtonPressed:
lda #StatusFireDown ; Button still down?
bit StatusBits
bne .NoRestart ; Then wait for release
setBit StatusFireDown, StatusBits
lda ActiveArea
cmp #ActiveAreaScores
bne .ButtonPressedReroll
setBit StatusPlayHand, StatusBits
jmp .NoRestart
.ButtonPressedReroll
lda ActiveArea
cmp #ActiveAreaReRoll
bne .buttonPressedDice
lda RollCount
beq .noReroll
jsr RerollDice
.noReroll
jmp .NoRestart
.buttonPressedDice:
jsr handleAreaDiceFire
jmp .NoRestart
.checkAreaScore:
lda GameState
cmp #TitleScreen
beq .Restart ; Start game if title screen
; cmp #GameOver ; or game over
bne .NoRestart
.Restart:
stx GameMode
jmp StartNewGame
.NoRestart:
;;;;;;;;;;;;;;;;;;;;
;; INPUT CHECKING ;;
;;;;;;;;;;;;;;;;;;;;
subroutine
; Joystick
lda SWCHA
; ldx CurrentPlayer
; beq VerifyGameStateForJoyCheck
; asl ; If it's P1's turn, put their bits where P0s
; asl ; would be
; asl
; asl
VerifyGameStateForJoyCheck:
and #JoyMask ; Only player 0 bits
ldx GameState ; We only care for states in which we are waiting
cpx #WaitingJoyRelease ; for a joystick press or release
beq CheckJoyRelease
ldx GameState ; We only care for states in which we are waiting
cpx #WaitingJoyPress
bne .scoresEndJoyCheck
; If the joystick is in one of these directions, trigger the shift by
; setting the ShiftVector and changing mode
CheckJoyUp:
cmp #JoyUp
bne CheckJoyDown
lda #JoyVectorUp
jmp TriggerShift
CheckJoyDown:
cmp #JoyDown
bne CheckJoyLeft
lda #JoyVectorDown
jmp TriggerShift
CheckJoyLeft:
cmp #JoyLeft
bne CheckJoyRight
lda #JoyVectorLeft
jmp TriggerShift
CheckJoyRight:
cmp #JoyRight
bne .scoresEndJoyCheck
lda #JoyVectorRight
TriggerShift:
sta MoveVector
lda #WaitingJoyRelease
sta GameState
jmp .scoresEndJoyCheck
CheckJoyRelease:
cmp #JoyMask
bne .scoresEndJoyCheck
lda ActiveArea
cmp #ActiveAreaScores
bne .dice
jmp checkJoyReleaseScores
.dice:
lda ActiveArea
cmp #ActiveAreaDice
bne .reroll
jmp CheckJoyReleaseDice
.reroll:
lda ActiveArea
cmp #ActiveAreaReRoll
bne .scoresEndJoyCheck
jmp CheckJoyReleaseReroll
.scoresEndJoyCheck
jmp EndJoyCheck
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Handle the joystick actions for the ScoreArea ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
checkJoyReleaseScores: subroutine
ldy OffsetIntoScoreList ; Save value
lda MoveVector
cmp #JoyVectorUp
bne .checkDownVector
inc OffsetIntoScoreList
jmp .CheckJoyReleaseEnd
.checkDownVector
lda MoveVector
cmp #JoyVectorDown
bne .checkLeftVector
dec OffsetIntoScoreList
jmp .CheckJoyReleaseEnd
.checkLeftVector:
cmp #JoyVectorLeft
bne .checkRightVector
lda #ActiveAreaDice
sta ActiveArea
jmp .CheckJoyReleaseEnd
.checkRightVector:
.CheckJoyReleaseEnd:
clc
lda ScreenLineIndex
adc OffsetIntoScoreList
bcs .CheckJoyReleaseRangeNotValid
cmp #MaxScoreLines-1
bcc .CheckJoyReleaseRangeValid
jmp .CheckJoyReleaseRangeNotValid
.CheckJoyReleaseRangeNotValid:
sty OffsetIntoScoreList
.CheckJoyReleaseRangeValid:
lda #WaitingJoyPress ; Joystick released, can accept shifts again
sta GameState
jmp EndJoyRelease
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Handle the joystick actions for the Dice Area ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CheckJoyReleaseDice: subroutine
ldy HighlightedDie
lda MoveVector
cmp #JoyVectorUp
bne .checkDownVector
lda #ActiveAreaScores
sta ActiveArea
jmp .CheckJoyReleaseEnd
.checkDownVector
lda MoveVector
cmp #JoyVectorDown
bne .checkLeftVector
lda #ActiveAreaReRoll
sta ActiveArea
jmp .CheckJoyReleaseEnd
.checkLeftVector:
cmp #JoyVectorLeft
bne .checkRightVector
dec HighlightedDie
jmp .CheckJoyReleaseEnd
.checkRightVector:
cmp #JoyVectorRight
bne .CheckJoyReleaseEnd
inc HighlightedDie
.CheckJoyReleaseEnd:
lda HighlightedDie
cmp #-1
bcs .CheckJoyReleaseRangeNotValid
cmp #DiceCount ; The number of dice
bcc .CheckJoyReleaseRangeValid
jmp .CheckJoyReleaseRangeNotValid
.CheckJoyReleaseRangeNotValid:
sty HighlightedDie
.CheckJoyReleaseRangeValid:
lda #WaitingJoyPress ; Joystick released, can accept shifts again
sta GameState
jmp EndJoyRelease
CheckJoyReleaseReroll: subroutine
lda MoveVector
cmp #JoyVectorUp
bne .checkDownVector
lda #ActiveAreaDice
sta ActiveArea
jmp EndJoyRelease
.checkDownVector:
nop
EndJoyRelease:
lda #WaitingJoyPress ; Joystick released, can accept shifts again
sta GameState
EndJoyCheck:
nop
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; REMAINDER OF OVERSCAN ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
subroutine
.WaitForOverscanEndLoop:
lda INTIM ; Wait until the timer signals the actual end
bne .WaitForOverscanEndLoop ; of the overscan period
sta WSYNC
jmp StartFrame
showDice: subroutine
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Reveal the dice that are in the shadow registers ;;
;; ;;
;; We use shadow registers because we turn the PF ;;
;; on and then off every scan line, keeping the ;;
;; dice display oo just the left-hand side. ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
lda MaskPF0
and SPF0
sta SPF0
lda MaskPF1
and SPF1
sta SPF1
lda MaskPF2
and SPF2
sta SPF2
subroutine
REPEAT DiceRowScanLines
sta WSYNC
; Copy the shadow registers
ldy SPF0
sty PF0
ldy SPF1
sty PF1
ldy SPF2
sty PF2
; Wait for playfield to be drawn
REPEAT 10-1
nop
REPEND
; And clear it before the other side.
ldy #0
sty PF0
sty PF1
sty PF2
REPEND
rts
CalcBlinkMask: subroutine
lda #$FF ; Don't mask out any bits
sta MaskPF0
sta MaskPF1
sta MaskPF2
lda #StatusBlinkOn
bit StatusBits
bne .checkRegion
rts
.checkRegion
lda ActiveArea
cmp #ActiveAreaDice
beq .setMasks
rts
.setMasks:
lda HighlightedDie
asl
tax
lda blinkLookup+1,x
pha
lda blinkLookup,x
pha
rts
.blink0
lda #$00
sta MaskPF0
rts
.blink1
lda #$0F
sta MaskPF1
rts
.blink2
lda #$F0
sta MaskPF1
rts
.blink3
lda #$F0
sta MaskPF2
rts
.blink4
lda #$0F
sta MaskPF2
rts
blinkLookup:
word .blink0 -1
word .blink1 -1
word .blink2 -1
word .blink3 -1
word .blink4 -1
handleAreaDiceFire: subroutine
lda #1 ; Load the first bit
ldx HighlightedDie ; And find which position
inx ; Start counting at 1
.l asl ; Shift it along
dex ; Counting down
bne .l ; Until we are there
lsr ; Make up for us starting at 1
eor RerollDiceMask ; Toggle the bit
sta RerollDiceMask ; And re-save
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintLabel: subroutine
lda #0 ; No players until we start
sta GRP0
sta GRP1
lda #>LabelBitmaps0 ; MSB of tiles/digits page
ldx #11 ; 12-byte table (6 digits), zero-based
.FillMsbLoop1:
sta GraphicBmpPtr,x
dex ; Skip to the next MSB
dex
bpl .FillMsbLoop1
sta HMCLR
; Score setup scanlines 2-3:
; player graphics triplicated and positioned like this: P0 P1 P0 P1 P0 P1
; also, set their colors
sta WSYNC ; !!
lda #PlayerThreeCopies ; (2)
sta NUSIZ0 ; (3)
sta NUSIZ1 ; (3)
lda #VerticalDelay ; (2) ; Needed for precise timing of GRP0/GRP1
sta VDELP0 ; (3)
sta VDELP1 ; (3)
REPEAT 10 ; (20=10x2) ; Delay to position right
nop
REPEND
sta RESP0 ; (3) ; Position P0
sta RESP1 ; (3) ; Position P1
sta WSYNC
lda #$E0 ; Fine-tune player positions to center on screen
sta HMP0
lda #$F0
sta HMP1
sta WSYNC
sta HMOVE ; (3)
; set the graphic pointers for each score digit
lda #<labelReroll5
sta GraphicBmpPtr + 10
lda #<labelReroll4
sta GraphicBmpPtr + 8
lda #<labelReroll3
sta GraphicBmpPtr + 6
lda #<labelReroll2
sta GraphicBmpPtr + 4
lda #<labelReroll1
sta GraphicBmpPtr + 2
lda #<labelReroll0
sta GraphicBmpPtr + 0
; Start checking custom values
lda PrintLabelID
cmp PrintLabelRoll1
bne .tryRoll2
lda #<Digitnum1
sta GraphicBmpPtr + 10
lda #>Digits
sta GraphicBmpPtr + 11
jmp .doneChecking
.tryRoll2
lda PrintLabelID
cmp PrintLabelRoll2
bne .tryRoll3
lda #<Digitnum2
sta GraphicBmpPtr + 10
lda #>Digits
sta GraphicBmpPtr + 11
jmp .doneChecking
.tryRoll3
lda PrintLabelID
cmp PrintLabelRoll3
bne .nextTest
lda #<Digitnum3
sta GraphicBmpPtr + 10
lda #>Digits
sta GraphicBmpPtr + 11
jmp .doneChecking
.nextTest
.doneChecking
; We may have been drawing the end of the grid (if it's P1 score)
lda #0
sta PF0
sta PF1
sta PF2
;;;;;;;;;;;
;; SCORE ;;
;;;;;;;;;;;
ldy #4 ; 5 scanlines
sty ScanLineCounter
.DrawScoreLoop:
ldy ScanLineCounter ; 6-digit loop is heavily inspired on Berzerk's
lda (GraphicBmpPtr),y
sta GRP0
sta WSYNC
lda (GraphicBmpPtr+2),y
sta GRP1
lda (GraphicBmpPtr+4),y
sta GRP0
lda (GraphicBmpPtr+6),y
sta TempDigitBmp
lda (GraphicBmpPtr+8),y
tax
lda (GraphicBmpPtr+10),y
tay
lda TempDigitBmp
sta GRP1
stx GRP0
sty GRP1
sta GRP0
dec ScanLineCounter
bpl .DrawScoreLoop
.ScoreCleanup: ; 1 scanline
lda #0
sta VDELP0
sta VDELP1
sta GRP0
sta GRP1
sta WSYNC
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Positions an object horizontally
; Inputs: A = Desired position.
; X = Desired object to be positioned (0-5).
; scanlines: If control comes on or before cycle 73 then 1 scanline is consumed.
; If control comes after cycle 73 then 2 scanlines are consumed.
; Outputs: X = unchanged
; A = Fine Adjustment value.
; Y = the "remainder" of the division by 15 minus an additional 15.
; control is returned on cycle 6 of the next scanline.
PosObject: subroutine
sta WSYNC ; 00 Sync to start of scanline.
sec ; 02 Set the carry flag so no borrow will be applied during the division.
.divideby15 sbc #15 ; 04 Waste the necessary amount of time dividing X-pos by 15!
bcs .divideby15 ; 06/07 11/16/21/26/31/36/41/46/51/56/61/66
tay
lda fineAdjustTable,y ; 13 -> Consume 5 cycles by guaranteeing we cross a page boundary
sta HMP0,x
sta RESP0,x ; 21/ 26/31/36/41/46/51/56/61/66/71 - Set the rough position./Pos
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; REROLL DICE ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
RerollDice: subroutine
lda #[1 << 0]
bit RerollDiceMask
beq .reroll1
jsr random_dice;
sta RolledDice + 0
.reroll1
lda #[1 << 1]
bit RerollDiceMask
beq .reroll2
jsr random_dice;
sta RolledDice + 1
.reroll2
lda #[1 << 2]
bit RerollDiceMask
beq .reroll3
jsr random_dice;
sta RolledDice + 2
.reroll3
lda #[1 << 3]
bit RerollDiceMask
beq .reroll4
jsr random_dice;
sta RolledDice + 3
.reroll4
lda #[1 << 4]
bit RerollDiceMask
beq .rerollDone
jsr random_dice;
sta RolledDice + 4
.rerollDone:
lda #0
sta RerollDiceMask
dec RollCount
rts
;;;;;;;;;;;;;;
;; NEW GAME ;;
;;;;;;;;;;;;;;
StartNewGame: subroutine
;;;;;;;;;;;;;;;;;;;;;;;;
;; Mark all the score slots as unscored
;;;;;;;;;;;;;;;;;;;;;;;
lda #Unscored
ldx #ScoreRamSize
.clearScores:
dex
sta score_low,x
bne .clearScores
lda #0
sta StatusBits ; Reset the game statuss
sta OffsetIntoScoreList ; Reset te top line
; Continue into real prep
lda #WaitingJoyPress
sta GameState
lda #ActiveAreaScores
sta ActiveArea
lda #ScorePhaseCalcUpper
sta ScorePhase
jsr StartNewRound
jmp StartFrame
StartNewRound: subroutine
lda #0
sta HighlightedDie
lda #RollsPerHand
sta RollCount
lda #%00011111
sta RerollDiceMask
jsr RerollDice
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Random number generator ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The RNG must be seeded with a non-zero value
;; To keep things "fresh" its recommended this be
;; called on every VBLANK.
random: subroutine
lda Rand8
lsr
ifconst Rand16
rol Rand16 ; this command is only used if Rand16 has been defined
endif
bcc .noeor
eor #$B4
.noeor
sta Rand8
ifconst Rand16
eor Rand16 ; this command is only used if Rand16 has been defined
endif
rts
;; Die value in the A register
random_dice:
jsr random
lda Rand8
and #%0000111
cmp #6
bcs random_dice
clc
adc #1
rts
include "calcscoring.asm"
;===============================================================================
; free space check before End of Cartridge
;===============================================================================
if (* & $FF)
echo "------", [$FFFA - *]d, "bytes free before End of Cartridge"
align 256
endif
;===============================================================================
; Define End of Cartridge
;===============================================================================
ORG $FFFA ; set address to 6507 Interrupt Vectors
.WORD Initialize
.WORD Initialize
.WORD Initialize
END
; The MIT License (MIT)
; Copyright (c) 2018 Jeremy J Starcher
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
|
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \brief Provides the seqan3::format_bam.
* \author Svenja Mehringer <svenja.mehringer AT fu-berlin.de>
*/
#pragma once
#include <seqan3/std/bit>
#include <iterator>
#include <seqan3/std/ranges>
#include <string>
#include <vector>
#include <seqan3/alphabet/nucleotide/dna16sam.hpp>
#include <seqan3/core/debug_stream/optional.hpp>
#include <seqan3/io/sam_file/detail/cigar.hpp>
#include <seqan3/io/sam_file/detail/format_sam_base.hpp>
#include <seqan3/io/sam_file/header.hpp>
#include <seqan3/io/sam_file/input_options.hpp>
#include <seqan3/io/sam_file/sam_flag.hpp>
#include <seqan3/io/sam_file/sam_tag_dictionary.hpp>
#include <seqan3/io/stream/detail/fast_ostreambuf_iterator.hpp>
#include <seqan3/io/views/detail/istreambuf_view.hpp>
#include <seqan3/io/views/detail/take_exactly_view.hpp>
#include <seqan3/utility/views/slice.hpp>
namespace seqan3
{
/*!\brief The BAM format.
* \implements AlignmentFileFormat
* \ingroup io_sam_file
*
* \details
*
* The BAM format is the binary version of the SAM format:
*
* \copydetails seqan3::format_sam
*/
class format_bam : private detail::format_sam_base
{
public:
/*!\name Constructors, destructor and assignment
* \{
*/
// string_buffer is of type std::string and has some problems with pre-C++11 ABI
format_bam() = default; //!< Defaulted.
format_bam(format_bam const &) = default; //!< Defaulted.
format_bam & operator=(format_bam const &) = default; //!< Defaulted.
format_bam(format_bam &&) = default; //!< Defaulted.
format_bam & operator=(format_bam &&) = default; //!< Defaulted.
~format_bam() = default; //!< Defaulted.
//!\}
//!\brief The valid file extensions for this format; note that you can modify this value.
static inline std::vector<std::string> file_extensions
{
{ "bam" }
};
protected:
template <typename stream_type, // constraints checked by file
typename seq_legal_alph_type,
typename ref_seqs_type,
typename ref_ids_type,
typename stream_pos_type,
typename seq_type,
typename id_type,
typename offset_type,
typename ref_seq_type,
typename ref_id_type,
typename ref_offset_type,
typename align_type,
typename cigar_type,
typename flag_type,
typename mapq_type,
typename qual_type,
typename mate_type,
typename tag_dict_type,
typename e_value_type,
typename bit_score_type>
void read_alignment_record(stream_type & stream,
sam_file_input_options<seq_legal_alph_type> const & SEQAN3_DOXYGEN_ONLY(options),
ref_seqs_type & ref_seqs,
sam_file_header<ref_ids_type> & header,
stream_pos_type & position_buffer,
seq_type & seq,
qual_type & qual,
id_type & id,
offset_type & offset,
ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
ref_id_type & ref_id,
ref_offset_type & ref_offset,
align_type & align,
cigar_type & cigar_vector,
flag_type & flag,
mapq_type & mapq,
mate_type & mate,
tag_dict_type & tag_dict,
e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score));
template <typename stream_type,
typename header_type,
typename seq_type,
typename id_type,
typename ref_seq_type,
typename ref_id_type,
typename align_type,
typename cigar_type,
typename qual_type,
typename mate_type,
typename tag_dict_type>
void write_alignment_record([[maybe_unused]] stream_type & stream,
[[maybe_unused]] sam_file_output_options const & options,
[[maybe_unused]] header_type && header,
[[maybe_unused]] seq_type && seq,
[[maybe_unused]] qual_type && qual,
[[maybe_unused]] id_type && id,
[[maybe_unused]] int32_t const offset,
[[maybe_unused]] ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
[[maybe_unused]] ref_id_type && ref_id,
[[maybe_unused]] std::optional<int32_t> ref_offset,
[[maybe_unused]] align_type && align,
[[maybe_unused]] cigar_type && cigar_vector,
[[maybe_unused]] sam_flag const flag,
[[maybe_unused]] uint8_t const mapq,
[[maybe_unused]] mate_type && mate,
[[maybe_unused]] tag_dict_type && tag_dict,
[[maybe_unused]] double SEQAN3_DOXYGEN_ONLY(e_value),
[[maybe_unused]] double SEQAN3_DOXYGEN_ONLY(bit_score));
private:
//!\brief A variable that tracks whether the content of header has been read or not.
bool header_was_read{false};
//!\brief Local buffer to read into while avoiding reallocation.
std::string string_buffer{};
//!\brief Stores all fixed length variables which can be read/written directly by reinterpreting the binary stream.
struct alignment_record_core
{ // naming corresponds to official SAM/BAM specifications
int32_t block_size; //!< The size in bytes of the whole BAM record.
int32_t refID; //!< The reference id the read was mapped to.
int32_t pos; //!< The begin position of the alignment.
uint32_t l_read_name:8; //!< The length of the read name including the \0 character.
uint32_t mapq:8; //!< The mapping quality.
uint32_t bin:16; //!< The bin number.
uint32_t n_cigar_op:16; //!< The number of cigar operations of the alignment.
sam_flag flag; //!< The flag value (uint16_t enum).
int32_t l_seq; //!< The number of bases of the read sequence.
int32_t next_refID; //!< The reference id of the mate.
int32_t next_pos; //!< The begin position of the mate alignment.
int32_t tlen; //!< The template length of the read and its mate.
};
//!\brief Converts a cigar op character to the rank according to the official BAM specifications.
static constexpr std::array<uint8_t, 256> char_to_sam_rank
{
[] () constexpr
{
std::array<uint8_t, 256> ret{};
using index_t = std::make_unsigned_t<char>;
// ret['M'] = 0; set anyway by initialization
ret[static_cast<index_t>('I')] = 1;
ret[static_cast<index_t>('D')] = 2;
ret[static_cast<index_t>('N')] = 3;
ret[static_cast<index_t>('S')] = 4;
ret[static_cast<index_t>('H')] = 5;
ret[static_cast<index_t>('P')] = 6;
ret[static_cast<index_t>('=')] = 7;
ret[static_cast<index_t>('X')] = 8;
return ret;
}()
};
//!\brief Computes the bin number for a given region [beg, end), copied from the official SAM specifications.
static uint16_t reg2bin(int32_t beg, int32_t end) noexcept
{
--end;
if (beg >> 14 == end >> 14) return ((1 << 15) - 1) / 7 + (beg >> 14);
if (beg >> 17 == end >> 17) return ((1 << 12) - 1) / 7 + (beg >> 17);
if (beg >> 20 == end >> 20) return ((1 << 9) - 1) / 7 + (beg >> 20);
if (beg >> 23 == end >> 23) return ((1 << 6) - 1) / 7 + (beg >> 23);
if (beg >> 26 == end >> 26) return ((1 << 3) - 1) / 7 + (beg >> 26);
return 0;
}
/*!\brief Reads a arithmetic field from binary stream by directly reinterpreting the bits.
* \tparam stream_view_type The type of the stream as a view.
* \tparam number_type The type of number to parse; must model std::integral.
* \param[in, out] stream_view The stream view to read from.
* \param[out] target An integral value to store the parsed value in.
*/
template <typename stream_view_type, std::integral number_type>
void read_integral_byte_field(stream_view_type && stream_view, number_type & target)
{
std::ranges::copy_n(std::ranges::begin(stream_view), sizeof(target), reinterpret_cast<char *>(&target));
}
/*!\brief Reads a float field from binary stream by directly reinterpreting the bits.
* \tparam stream_view_type The type of the stream as a view.
* \param[in, out] stream_view The stream view to read from.
* \param[out] target An float value to store the parsed value in.
*/
template <typename stream_view_type>
void read_float_byte_field(stream_view_type && stream_view, float & target)
{
std::ranges::copy_n(std::ranges::begin(stream_view), sizeof(int32_t), reinterpret_cast<char *>(&target));
}
template <typename stream_view_type, typename value_type>
void read_sam_dict_vector(seqan3::detail::sam_tag_variant & variant,
stream_view_type && stream_view,
value_type const & SEQAN3_DOXYGEN_ONLY(value));
template <typename stream_view_type>
void read_sam_dict_field(stream_view_type && stream_view, sam_tag_dictionary & target);
template <typename cigar_input_type>
auto parse_binary_cigar(cigar_input_type && cigar_input, uint16_t n_cigar_op) const;
static std::string get_tag_dict_str(sam_tag_dictionary const & tag_dict);
};
//!\copydoc sam_file_input_format::read_alignment_record
template <typename stream_type, // constraints checked by file
typename seq_legal_alph_type,
typename ref_seqs_type,
typename ref_ids_type,
typename stream_pos_type,
typename seq_type,
typename id_type,
typename offset_type,
typename ref_seq_type,
typename ref_id_type,
typename ref_offset_type,
typename align_type,
typename cigar_type,
typename flag_type,
typename mapq_type,
typename qual_type,
typename mate_type,
typename tag_dict_type,
typename e_value_type,
typename bit_score_type>
inline void format_bam::read_alignment_record(stream_type & stream,
sam_file_input_options<seq_legal_alph_type> const & SEQAN3_DOXYGEN_ONLY(options),
ref_seqs_type & ref_seqs,
sam_file_header<ref_ids_type> & header,
stream_pos_type & position_buffer,
seq_type & seq,
qual_type & qual,
id_type & id,
offset_type & offset,
ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
ref_id_type & ref_id,
ref_offset_type & ref_offset,
align_type & align,
cigar_type & cigar_vector,
flag_type & flag,
mapq_type & mapq,
mate_type & mate,
tag_dict_type & tag_dict,
e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score))
{
static_assert(detail::decays_to_ignore_v<ref_offset_type> ||
detail::is_type_specialisation_of_v<ref_offset_type, std::optional>,
"The ref_offset must be a specialisation of std::optional.");
static_assert(detail::decays_to_ignore_v<mapq_type> || std::same_as<mapq_type, uint8_t>,
"The type of field::mapq must be uint8_t.");
static_assert(detail::decays_to_ignore_v<flag_type> || std::same_as<flag_type, sam_flag>,
"The type of field::flag must be seqan3::sam_flag.");
auto stream_view = seqan3::detail::istreambuf(stream);
// these variables need to be stored to compute the ALIGNMENT
[[maybe_unused]] int32_t offset_tmp{};
[[maybe_unused]] int32_t soft_clipping_end{};
[[maybe_unused]] std::vector<cigar> tmp_cigar_vector{};
[[maybe_unused]] int32_t ref_length{0}, seq_length{0}; // length of aligned part for ref and query
// Header
// -------------------------------------------------------------------------------------------------------------
if (!header_was_read)
{
// magic BAM string
if (!std::ranges::equal(stream_view | detail::take_exactly_or_throw(4), std::string_view{"BAM\1"}))
throw format_error{"File is not in BAM format."};
int32_t l_text{}; // length of header text including \0 character
int32_t n_ref{}; // number of reference sequences
int32_t l_name{}; // 1 + length of reference name including \0 character
int32_t l_ref{}; // length of reference sequence
read_integral_byte_field(stream_view, l_text);
if (l_text > 0) // header text is present
read_header(stream_view | detail::take_exactly_or_throw(l_text), header, ref_seqs);
read_integral_byte_field(stream_view, n_ref);
for (int32_t ref_idx = 0; ref_idx < n_ref; ++ref_idx)
{
read_integral_byte_field(stream_view, l_name);
string_buffer.resize(l_name - 1);
std::ranges::copy_n(std::ranges::begin(stream_view), l_name - 1, string_buffer.data()); // copy without \0 character
++std::ranges::begin(stream_view); // skip \0 character
read_integral_byte_field(stream_view, l_ref);
if constexpr (detail::decays_to_ignore_v<ref_seqs_type>) // no reference information given
{
// If there was no header text, we parse reference sequences block as header information
if (l_text == 0)
{
auto & reference_ids = header.ref_ids();
// put the length of the reference sequence into ref_id_info
header.ref_id_info.emplace_back(l_ref, "");
// put the reference name into reference_ids
reference_ids.push_back(string_buffer);
// assign the reference name an ascending reference id (starts at index 0).
header.ref_dict.emplace(reference_ids.back(), reference_ids.size() - 1);
continue;
}
}
auto id_it = header.ref_dict.find(string_buffer);
// sanity checks of reference information to existing header object:
if (id_it == header.ref_dict.end()) // [unlikely]
{
throw format_error{detail::to_string("Unknown reference name '" + string_buffer +
"' found in BAM file header (header.ref_ids():",
header.ref_ids(), ").")};
}
else if (id_it->second != ref_idx) // [unlikely]
{
throw format_error{detail::to_string("Reference id '", string_buffer, "' at position ", ref_idx,
" does not correspond to the position ", id_it->second,
" in the header (header.ref_ids():", header.ref_ids(), ").")};
}
else if (std::get<0>(header.ref_id_info[id_it->second]) != l_ref) // [unlikely]
{
throw format_error{"Provided reference has unequal length as specified in the header."};
}
}
header_was_read = true;
if (std::ranges::begin(stream_view) == std::ranges::end(stream_view)) // no records follow
return;
}
// read alignment record into buffer
// -------------------------------------------------------------------------------------------------------------
position_buffer = stream.tellg();
alignment_record_core core;
std::ranges::copy(stream_view | detail::take_exactly_or_throw(sizeof(core)), reinterpret_cast<char *>(&core));
if (core.refID >= static_cast<int32_t>(header.ref_ids().size()) || core.refID < -1) // [[unlikely]]
{
throw format_error{detail::to_string("Reference id index '", core.refID, "' is not in range of ",
"header.ref_ids(), which has size ", header.ref_ids().size(), ".")};
}
else if (core.refID > -1) // not unmapped
{
ref_id = core.refID; // field::ref_id
}
flag = core.flag; // field::flag
mapq = core.mapq; // field::mapq
if (core.pos > -1) // [[likely]]
ref_offset = core.pos; // field::ref_offset
if constexpr (!detail::decays_to_ignore_v<mate_type>) // field::mate
{
if (core.next_refID > -1)
get<0>(mate) = core.next_refID;
if (core.next_pos > -1) // [[likely]]
get<1>(mate) = core.next_pos;
get<2>(mate) = core.tlen;
}
// read id
// -------------------------------------------------------------------------------------------------------------
auto id_view = stream_view | detail::take_exactly_or_throw(core.l_read_name - 1);
if constexpr (!detail::decays_to_ignore_v<id_type>)
read_forward_range_field(id_view, id); // field::id
else
detail::consume(id_view);
++std::ranges::begin(stream_view); // skip '\0'
// read cigar string
// -------------------------------------------------------------------------------------------------------------
if constexpr (!detail::decays_to_ignore_v<align_type> || !detail::decays_to_ignore_v<cigar_type>)
{
std::tie(tmp_cigar_vector, ref_length, seq_length) = parse_binary_cigar(stream_view, core.n_cigar_op);
transfer_soft_clipping_to(tmp_cigar_vector, offset_tmp, soft_clipping_end);
// the actual cigar_vector is swapped with tmp_cigar_vector at the end to avoid copying
}
else
{
detail::consume(stream_view | detail::take_exactly_or_throw(core.n_cigar_op * 4));
}
offset = offset_tmp;
// read sequence
// -------------------------------------------------------------------------------------------------------------
if (core.l_seq > 0) // sequence information is given
{
auto seq_stream = stream_view
| detail::take_exactly_or_throw(core.l_seq / 2) // one too short if uneven
| std::views::transform([] (char c) -> std::pair<dna16sam, dna16sam>
{
return {dna16sam{}.assign_rank(std::min(15, static_cast<uint8_t>(c) >> 4)),
dna16sam{}.assign_rank(std::min(15, static_cast<uint8_t>(c) & 0x0f))};
});
if constexpr (detail::decays_to_ignore_v<seq_type>)
{
auto skip_sequence_bytes = [&] ()
{
detail::consume(seq_stream);
if (core.l_seq & 1)
++std::ranges::begin(stream_view);
};
if constexpr (!detail::decays_to_ignore_v<align_type>)
{
static_assert(sequence_container<std::remove_reference_t<decltype(get<1>(align))>>,
"If you want to read ALIGNMENT but not SEQ, the alignment"
" object must store a sequence container at the second (query) position.");
if (!tmp_cigar_vector.empty()) // only parse alignment if cigar information was given
{
assert(core.l_seq == (seq_length + offset_tmp + soft_clipping_end)); // sanity check
using alph_t = std::ranges::range_value_t<decltype(get<1>(align))>;
constexpr auto from_dna16 = detail::convert_through_char_representation<alph_t, dna16sam>;
get<1>(align).reserve(seq_length);
auto tmp_iter = std::ranges::begin(seq_stream);
std::ranges::advance(tmp_iter, offset_tmp / 2); // skip soft clipped bases at the beginning
if (offset_tmp & 1)
{
get<1>(align).push_back(from_dna16[to_rank(get<1>(*tmp_iter))]);
++tmp_iter;
--seq_length;
}
for (size_t i = (seq_length / 2); i > 0; --i)
{
get<1>(align).push_back(from_dna16[to_rank(get<0>(*tmp_iter))]);
get<1>(align).push_back(from_dna16[to_rank(get<1>(*tmp_iter))]);
++tmp_iter;
}
if (seq_length & 1)
{
get<1>(align).push_back(from_dna16[to_rank(get<0>(*tmp_iter))]);
++tmp_iter;
--soft_clipping_end;
}
std::ranges::advance(tmp_iter, (soft_clipping_end + !(seq_length & 1)) / 2);
}
else
{
skip_sequence_bytes();
get<1>(align) = std::remove_reference_t<decltype(get<1>(align))>{}; // assign empty container
}
}
else
{
skip_sequence_bytes();
}
}
else
{
using alph_t = std::ranges::range_value_t<decltype(seq)>;
constexpr auto from_dna16 = detail::convert_through_char_representation<alph_t, dna16sam>;
for (auto [d1, d2] : seq_stream)
{
seq.push_back(from_dna16[to_rank(d1)]);
seq.push_back(from_dna16[to_rank(d2)]);
}
if (core.l_seq & 1)
{
dna16sam d = dna16sam{}.assign_rank(std::min(15, static_cast<uint8_t>(*std::ranges::begin(stream_view)) >> 4));
seq.push_back(from_dna16[to_rank(d)]);
++std::ranges::begin(stream_view);
}
if constexpr (!detail::decays_to_ignore_v<align_type>)
{
assign_unaligned(get<1>(align),
seq | views::slice(static_cast<std::ranges::range_difference_t<seq_type>>(offset_tmp),
std::ranges::distance(seq) - soft_clipping_end));
}
}
}
// read qual string
// -------------------------------------------------------------------------------------------------------------
auto qual_view = stream_view | detail::take_exactly_or_throw(core.l_seq)
| std::views::transform([] (char chr)
{
return static_cast<char>(chr + 33);
});
if constexpr (!detail::decays_to_ignore_v<qual_type>)
read_forward_range_field(qual_view, qual);
else
detail::consume(qual_view);
// All remaining optional fields if any: SAM tags dictionary
// -------------------------------------------------------------------------------------------------------------
int32_t remaining_bytes = core.block_size - (sizeof(alignment_record_core) - 4/*block_size excluded*/) -
core.l_read_name - core.n_cigar_op * 4 - (core.l_seq + 1) / 2 - core.l_seq;
assert(remaining_bytes >= 0);
auto tags_view = stream_view | detail::take_exactly_or_throw(remaining_bytes);
while (tags_view.size() > 0)
{
if constexpr (!detail::decays_to_ignore_v<tag_dict_type>)
read_sam_dict_field(tags_view, tag_dict);
else
detail::consume(tags_view);
}
// DONE READING - wrap up
// -------------------------------------------------------------------------------------------------------------
if constexpr (!detail::decays_to_ignore_v<align_type> || !detail::decays_to_ignore_v<cigar_type>)
{
// Check cigar, if it matches ‘kSmN’, where ‘k’ equals lseq, ‘m’ is the reference sequence length in the
// alignment, and ‘S’ and ‘N’ are the soft-clipping and reference-clip, then the cigar string was larger
// than 65535 operations and is stored in the sam_tag_dictionary (tag GC).
if (core.l_seq != 0 && offset_tmp == core.l_seq)
{
if constexpr (detail::decays_to_ignore_v<tag_dict_type> | detail::decays_to_ignore_v<seq_type>)
{ // maybe only throw in debug mode and otherwise return an empty alignment?
throw format_error{detail::to_string("The cigar string '", offset_tmp, "S", ref_length,
"N' suggests that the cigar string exceeded 65535 elements and was therefore ",
"stored in the optional field CG. You need to read in the field::tags and "
"field::seq in order to access this information.")};
}
else
{
auto it = tag_dict.find("CG"_tag);
if (it == tag_dict.end())
throw format_error{detail::to_string("The cigar string '", offset_tmp, "S", ref_length,
"N' suggests that the cigar string exceeded 65535 elements and was therefore ",
"stored in the optional field CG but this tag is not present in the given ",
"record.")};
auto cigar_view = std::views::all(std::get<std::string>(it->second));
std::tie(tmp_cigar_vector, ref_length, seq_length) = detail::parse_cigar(cigar_view);
offset_tmp = soft_clipping_end = 0;
transfer_soft_clipping_to(tmp_cigar_vector, offset_tmp, soft_clipping_end);
tag_dict.erase(it); // remove redundant information
if constexpr (!detail::decays_to_ignore_v<align_type>)
{
assign_unaligned(get<1>(align),
seq | views::slice(static_cast<std::ranges::range_difference_t<seq_type>>(offset_tmp),
std::ranges::distance(seq) - soft_clipping_end));
}
}
}
}
// Alignment object construction
if constexpr (!detail::decays_to_ignore_v<align_type>)
construct_alignment(align, tmp_cigar_vector, core.refID, ref_seqs, core.pos, ref_length); // inherited from SAM
if constexpr (!detail::decays_to_ignore_v<cigar_type>)
std::swap(cigar_vector, tmp_cigar_vector);
}
//!\copydoc sam_file_output_format::write_alignment_record
template <typename stream_type,
typename header_type,
typename seq_type,
typename id_type,
typename ref_seq_type,
typename ref_id_type,
typename align_type,
typename cigar_type,
typename qual_type,
typename mate_type,
typename tag_dict_type>
inline void format_bam::write_alignment_record([[maybe_unused]] stream_type & stream,
[[maybe_unused]] sam_file_output_options const & options,
[[maybe_unused]] header_type && header,
[[maybe_unused]] seq_type && seq,
[[maybe_unused]] qual_type && qual,
[[maybe_unused]] id_type && id,
[[maybe_unused]] int32_t const offset,
[[maybe_unused]] ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
[[maybe_unused]] ref_id_type && ref_id,
[[maybe_unused]] std::optional<int32_t> ref_offset,
[[maybe_unused]] align_type && align,
[[maybe_unused]] cigar_type && cigar_vector,
[[maybe_unused]] sam_flag const flag,
[[maybe_unused]] uint8_t const mapq,
[[maybe_unused]] mate_type && mate,
[[maybe_unused]] tag_dict_type && tag_dict,
[[maybe_unused]] double SEQAN3_DOXYGEN_ONLY(e_value),
[[maybe_unused]] double SEQAN3_DOXYGEN_ONLY(bit_score))
{
// ---------------------------------------------------------------------
// Type Requirements (as static asserts for user friendliness)
// ---------------------------------------------------------------------
static_assert((std::ranges::forward_range<seq_type> &&
alphabet<std::ranges::range_reference_t<seq_type>>),
"The seq object must be a std::ranges::forward_range over "
"letters that model seqan3::alphabet.");
static_assert((std::ranges::forward_range<id_type> &&
alphabet<std::ranges::range_reference_t<id_type>>),
"The id object must be a std::ranges::forward_range over "
"letters that model seqan3::alphabet.");
static_assert((std::ranges::forward_range<ref_seq_type> &&
alphabet<std::ranges::range_reference_t<ref_seq_type>>),
"The ref_seq object must be a std::ranges::forward_range "
"over letters that model seqan3::alphabet.");
if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
{
static_assert((std::ranges::forward_range<ref_id_type> ||
std::integral<std::remove_reference_t<ref_id_type>> ||
detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>),
"The ref_id object must be a std::ranges::forward_range "
"over letters that model seqan3::alphabet or an integral or a std::optional<integral>.");
}
static_assert(tuple_like<std::remove_cvref_t<align_type>>,
"The align object must be a std::pair of two ranges whose "
"value_type is comparable to seqan3::gap");
static_assert((std::tuple_size_v<std::remove_cvref_t<align_type>> == 2 &&
std::equality_comparable_with<gap, std::ranges::range_reference_t<decltype(std::get<0>(align))>> &&
std::equality_comparable_with<gap, std::ranges::range_reference_t<decltype(std::get<1>(align))>>),
"The align object must be a std::pair of two ranges whose "
"value_type is comparable to seqan3::gap");
static_assert((std::ranges::forward_range<qual_type> &&
alphabet<std::ranges::range_reference_t<qual_type>>),
"The qual object must be a std::ranges::forward_range "
"over letters that model seqan3::alphabet.");
static_assert(tuple_like<std::remove_cvref_t<mate_type>>,
"The mate object must be a std::tuple of size 3 with "
"1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
"2) a std::integral or std::optional<std::integral>, and "
"3) a std::integral.");
static_assert(((std::ranges::forward_range<decltype(std::get<0>(mate))> ||
std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>> ||
detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<0>(mate))>, std::optional>) &&
(std::integral<std::remove_cvref_t<decltype(std::get<1>(mate))>> ||
detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<1>(mate))>, std::optional>) &&
std::integral<std::remove_cvref_t<decltype(std::get<2>(mate))>>),
"The mate object must be a std::tuple of size 3 with "
"1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
"2) a std::integral or std::optional<std::integral>, and "
"3) a std::integral.");
static_assert(std::same_as<std::remove_cvref_t<tag_dict_type>, sam_tag_dictionary>,
"The tag_dict object must be of type seqan3::sam_tag_dictionary.");
if constexpr (detail::decays_to_ignore_v<header_type>)
{
throw format_error{"BAM can only be written with a header but you did not provide enough information! "
"You can either construct the output file with ref_ids and ref_seqs information and "
"the header will be created for you, or you can access the `header` member directly."};
}
else
{
// ---------------------------------------------------------------------
// logical Requirements
// ---------------------------------------------------------------------
if (ref_offset.has_value() && (ref_offset.value() + 1) < 0)
throw format_error{detail::to_string("The ref_offset object must be >= -1 but is: ", ref_offset)};
detail::fast_ostreambuf_iterator stream_it{*stream.rdbuf()};
// ---------------------------------------------------------------------
// Writing the BAM Header on first call
// ---------------------------------------------------------------------
if (!header_was_written)
{
stream << "BAM\1";
std::ostringstream os;
write_header(os, options, header); // write SAM header to temporary stream to query the size.
int32_t l_text{static_cast<int32_t>(os.str().size())};
std::ranges::copy_n(reinterpret_cast<char *>(&l_text), 4, stream_it); // write read id
stream << os.str();
int32_t n_ref{static_cast<int32_t>(header.ref_ids().size())};
std::ranges::copy_n(reinterpret_cast<char *>(&n_ref), 4, stream_it); // write read id
for (int32_t ridx = 0; ridx < n_ref; ++ridx)
{
int32_t l_name{static_cast<int32_t>(header.ref_ids()[ridx].size()) + 1}; // plus null character
std::ranges::copy_n(reinterpret_cast<char *>(&l_name), 4, stream_it); // write l_name
// write reference name:
std::ranges::copy(header.ref_ids()[ridx].begin(), header.ref_ids()[ridx].end(), stream_it);
stream_it = '\0';
// write reference sequence length:
std::ranges::copy_n(reinterpret_cast<char *>(&get<0>(header.ref_id_info[ridx])), 4, stream_it);
}
header_was_written = true;
}
// ---------------------------------------------------------------------
// Writing the Record
// ---------------------------------------------------------------------
int32_t ref_length{};
// if alignment is non-empty, replace cigar_vector.
// else, compute the ref_length from given cigar_vector which is needed to fill field `bin`.
if (!std::ranges::empty(cigar_vector))
{
int32_t dummy_seq_length{};
for (auto & [count, operation] : cigar_vector)
detail::update_alignment_lengths(ref_length, dummy_seq_length, operation.to_char(), count);
}
else if (!std::ranges::empty(get<0>(align)) && !std::ranges::empty(get<1>(align)))
{
ref_length = std::ranges::distance(get<1>(align));
// compute possible distance from alignment end to sequence end
// which indicates soft clipping at the end.
// This should be replaced by a free count_gaps function for
// aligned sequences which is more efficient if possible.
int32_t off_end{static_cast<int32_t>(std::ranges::distance(seq)) - offset};
for (auto chr : get<1>(align))
if (chr == gap{})
++off_end;
off_end -= ref_length;
cigar_vector = detail::get_cigar_vector(align, offset, off_end);
}
if (cigar_vector.size() >= (1 << 16)) // must be written into the sam tag CG
{
tag_dict["CG"_tag] = detail::get_cigar_string(cigar_vector);
cigar_vector.resize(2);
cigar_vector[0] = cigar{static_cast<uint32_t>(std::ranges::distance(seq)), 'S'_cigar_operation};
cigar_vector[1] = cigar{static_cast<uint32_t>(std::ranges::distance(get<1>(align))), 'N'_cigar_operation};
}
std::string tag_dict_binary_str = get_tag_dict_str(tag_dict);
// Compute the value for the l_read_name field for the bam record.
// This value is stored including a trailing `0`, so at most 254 characters of the id can be stored, since
// the data type to store the value is uint8_t and 255 is the maximal size.
// If the id is empty a '*' is written instead, i.e. the written id is never an empty string and stores at least
// 2 bytes.
uint8_t read_name_size = std::min<uint8_t>(std::ranges::distance(id), 254) + 1;
read_name_size += static_cast<uint8_t>(read_name_size == 1); // need size two since empty id is stored as '*'.
alignment_record_core core
{
/* block_size */ 0, // will be initialised right after
/* refID */ -1, // will be initialised right after
/* pos */ ref_offset.value_or(-1),
/* l_read_name */ read_name_size,
/* mapq */ mapq,
/* bin */ reg2bin(ref_offset.value_or(-1), ref_length),
/* n_cigar_op */ static_cast<uint16_t>(cigar_vector.size()),
/* flag */ flag,
/* l_seq */ static_cast<int32_t>(std::ranges::distance(seq)),
/* next_refId */ -1, // will be initialised right after
/* next_pos */ get<1>(mate).value_or(-1),
/* tlen */ get<2>(mate)
};
auto check_and_assign_id_to = [&header] ([[maybe_unused]] auto & id_source,
[[maybe_unused]] auto & id_target)
{
using id_t = std::remove_reference_t<decltype(id_source)>;
if constexpr (!detail::decays_to_ignore_v<id_t>)
{
if constexpr (std::integral<id_t>)
{
id_target = id_source;
}
else if constexpr (detail::is_type_specialisation_of_v<id_t, std::optional>)
{
id_target = id_source.value_or(-1);
}
else
{
if (!std::ranges::empty(id_source)) // otherwise default will remain (-1)
{
auto id_it = header.ref_dict.end();
if constexpr (std::ranges::contiguous_range<decltype(id_source)> &&
std::ranges::sized_range<decltype(id_source)> &&
std::ranges::borrowed_range<decltype(id_source)>)
{
id_it = header.ref_dict.find(std::span{std::ranges::data(id_source),
std::ranges::size(id_source)});
}
else
{
using header_ref_id_type = std::remove_reference_t<decltype(header.ref_ids()[0])>;
static_assert(implicitly_convertible_to<decltype(id_source), header_ref_id_type>,
"The ref_id type is not convertible to the reference id information stored in the "
"reference dictionary of the header object.");
id_it = header.ref_dict.find(id_source);
}
if (id_it == header.ref_dict.end())
{
throw format_error{detail::to_string("Unknown reference name '", id_source, "' could "
"not be found in BAM header ref_dict: ",
header.ref_dict, ".")};
}
id_target = id_it->second;
}
}
}
};
// initialise core.refID
check_and_assign_id_to(ref_id, core.refID);
// initialise core.next_refID
check_and_assign_id_to(get<0>(mate), core.next_refID);
// initialise core.block_size
core.block_size = sizeof(core) - 4/*block_size excluded*/ +
core.l_read_name +
core.n_cigar_op * 4 + // each int32_t has 4 bytes
(core.l_seq + 1) / 2 + // bitcompressed seq
core.l_seq + // quality string
tag_dict_binary_str.size();
std::ranges::copy_n(reinterpret_cast<char *>(&core), sizeof(core), stream_it); // write core
if (std::ranges::empty(id)) // empty id is represented as * for backward compatibility
stream_it = '*';
else
std::ranges::copy_n(std::ranges::begin(id), core.l_read_name - 1, stream_it); // write read id
stream_it = '\0';
// write cigar
for (auto [cigar_count, op] : cigar_vector)
{
cigar_count = cigar_count << 4;
cigar_count |= static_cast<int32_t>(char_to_sam_rank[op.to_char()]);
std::ranges::copy_n(reinterpret_cast<char *>(&cigar_count), 4, stream_it);
}
// write seq (bit-compressed: dna16sam characters go into one byte)
using alph_t = std::ranges::range_value_t<seq_type>;
constexpr auto to_dna16 = detail::convert_through_char_representation<dna16sam, alph_t>;
auto sit = std::ranges::begin(seq);
for (int32_t sidx = 0; sidx < ((core.l_seq & 1) ? core.l_seq - 1 : core.l_seq); ++sidx, ++sit)
{
uint8_t compressed_chr = to_rank(to_dna16[to_rank(*sit)]) << 4;
++sidx, ++sit;
compressed_chr |= to_rank(to_dna16[to_rank(*sit)]);
stream_it = static_cast<char>(compressed_chr);
}
if (core.l_seq & 1) // write one more
stream_it = static_cast<char>(to_rank(to_dna16[to_rank(*sit)]) << 4);
// write qual
if (std::ranges::empty(qual))
{
auto v = views::repeat_n(static_cast<char>(255), core.l_seq);
std::ranges::copy_n(v.begin(), core.l_seq, stream_it);
}
else
{
if (std::ranges::distance(qual) != core.l_seq)
throw format_error{detail::to_string("Expected quality of same length as sequence with size ",
core.l_seq, ". Got quality with size ",
std::ranges::distance(qual), " instead.")};
auto v = qual | std::views::transform([] (auto chr) { return static_cast<char>(to_rank(chr)); });
std::ranges::copy_n(v.begin(), core.l_seq, stream_it);
}
// write optional fields
stream << tag_dict_binary_str;
} // if constexpr (!detail::decays_to_ignore_v<header_type>)
}
//!\copydoc seqan3::format_sam::read_sam_dict_vector
template <typename stream_view_type, typename value_type>
inline void format_bam::read_sam_dict_vector(seqan3::detail::sam_tag_variant & variant,
stream_view_type && stream_view,
value_type const & SEQAN3_DOXYGEN_ONLY(value))
{
int32_t count;
read_integral_byte_field(stream_view, count); // read length of vector
std::vector<value_type> tmp_vector;
tmp_vector.reserve(count);
while (count > 0)
{
value_type tmp{};
if constexpr(std::integral<value_type>)
{
read_integral_byte_field(stream_view, tmp);
}
else if constexpr(std::same_as<value_type, float>)
{
read_float_byte_field(stream_view, tmp);
}
else
{
constexpr bool always_false = std::is_same_v<value_type, void>;
static_assert(always_false, "format_bam::read_sam_dict_vector: unsupported value_type");
}
tmp_vector.push_back(std::move(tmp));
--count;
}
variant = std::move(tmp_vector);
}
/*!\brief Reads the optional tag fields into the seqan3::sam_tag_dictionary.
* \tparam stream_view_type The type of the stream as a view.
*
* \param[in, out] stream_view The stream view to iterate over.
* \param[out] target The seqan3::sam_tag_dictionary to store the tag information.
*
* \throws seqan3::format_error if any unexpected character or format is encountered.
*
* \details
*
* Reading the tags is done according to the official
* [SAM format specifications](https://samtools.github.io/hts-specs/SAMv1.pdf).
*
* The function throws a seqan3::format_error if any unknown tag type was encountered. It will also fail if the
* format is not in a correct state (e.g. required fields are not given), but throwing might occur downstream of
* the actual error.
*/
template <typename stream_view_type>
inline void format_bam::read_sam_dict_field(stream_view_type && stream_view, sam_tag_dictionary & target)
{
/* Every BA< tag has the format "[TAG][TYPE_ID][VALUE]", where TAG is a two letter
name tag which is converted to a unique integer identifier and TYPE_ID is one character in [A,i,Z,H,B,f]
describing the type for the upcoming VALUES. If TYPE_ID=='B' it signals an array of
VALUE's and the inner value type is identified by the next character, one of [cCsSiIf], followed
by the length (int32_t) of the array, followed by the values.
*/
auto it = std::ranges::begin(stream_view);
uint16_t tag = static_cast<uint16_t>(*it) << 8;
++it; // skip char read before
tag += static_cast<uint16_t>(*it);
++it; // skip char read before
char type_id = *it;
++it; // skip char read before
switch (type_id)
{
case 'A' : // char
{
target[tag] = *it;
++it; // skip char that has been read
break;
}
// all integer sizes are possible
case 'c' : // int8_t
{
int8_t tmp;
read_integral_byte_field(stream_view, tmp);
target[tag] = static_cast<int32_t>(tmp); // readable sam format only allows int32_t
break;
}
case 'C' : // uint8_t
{
uint8_t tmp;
read_integral_byte_field(stream_view, tmp);
target[tag] = static_cast<int32_t>(tmp); // readable sam format only allows int32_t
break;
}
case 's' : // int16_t
{
int16_t tmp;
read_integral_byte_field(stream_view, tmp);
target[tag] = static_cast<int32_t>(tmp); // readable sam format only allows int32_t
break;
}
case 'S' : // uint16_t
{
uint16_t tmp;
read_integral_byte_field(stream_view, tmp);
target[tag] = static_cast<int32_t>(tmp); // readable sam format only allows int32_t
break;
}
case 'i' : // int32_t
{
int32_t tmp;
read_integral_byte_field(stream_view, tmp);
target[tag] = std::move(tmp); // readable sam format only allows int32_t
break;
}
case 'I' : // uint32_t
{
uint32_t tmp;
read_integral_byte_field(stream_view, tmp);
target[tag] = static_cast<int32_t>(tmp); // readable sam format only allows int32_t
break;
}
case 'f' : // float
{
float tmp;
read_float_byte_field(stream_view, tmp);
target[tag] = tmp;
break;
}
case 'Z' : // string
{
string_buffer.clear();
while (!is_char<'\0'>(*it))
{
string_buffer.push_back(*it);
++it;
}
++it; // skip \0
target[tag] = string_buffer;
break;
}
case 'H' : // byte array, represented as null-terminated string; specification requires even number of bytes
{
std::vector<std::byte> byte_array;
std::byte value;
while (!is_char<'\0'>(*it))
{
string_buffer.clear();
string_buffer.push_back(*it);
++it;
if (*it == '\0')
throw format_error{"Hexadecimal tag has an uneven number of digits!"};
string_buffer.push_back(*it);
++it;
read_byte_field(string_buffer, value);
byte_array.push_back(value);
}
++it; // skip \0
target[tag] = byte_array;
break;
}
case 'B' : // Array. Value type depends on second char [cCsSiIf]
{
char array_value_type_id = *it;
++it; // skip char read before
switch (array_value_type_id)
{
case 'c' : // int8_t
read_sam_dict_vector(target[tag], stream_view, int8_t{});
break;
case 'C' : // uint8_t
read_sam_dict_vector(target[tag], stream_view, uint8_t{});
break;
case 's' : // int16_t
read_sam_dict_vector(target[tag], stream_view, int16_t{});
break;
case 'S' : // uint16_t
read_sam_dict_vector(target[tag], stream_view, uint16_t{});
break;
case 'i' : // int32_t
read_sam_dict_vector(target[tag], stream_view, int32_t{});
break;
case 'I' : // uint32_t
read_sam_dict_vector(target[tag], stream_view, uint32_t{});
break;
case 'f' : // float
read_sam_dict_vector(target[tag], stream_view, float{});
break;
default:
throw format_error{detail::to_string("The first character in the numerical id of a SAM tag ",
"must be one of [cCsSiIf] but '", array_value_type_id, "' was given.")};
}
break;
}
default:
throw format_error{detail::to_string("The second character in the numerical id of a "
"SAM tag must be one of [A,i,Z,H,B,f] but '", type_id, "' was given.")};
}
}
/*!\brief Parses a cigar string into a vector of operation-count pairs (e.g. (M, 3)).
* \tparam cigar_input_type The type of a single pass input view over the cigar string; must model
* std::ranges::input_range.
* \param[in] cigar_input The single pass input view over the cigar string to parse.
* \param[in] n_cigar_op The number of cigar elements to read from the cigar_input.
*
* \returns A tuple of size three containing (1) std::vector over seqan3::cigar, that describes
* the alignment, (2) the aligned reference length, (3) the aligned query sequence length.
*
* \details
*
* For example, the view over the cigar string "1H4M1D2M2S" will return
* `{[(H,1), (M,4), (D,1), (M,2), (S,2)], 7, 6}`.
*/
template <typename cigar_input_type>
inline auto format_bam::parse_binary_cigar(cigar_input_type && cigar_input, uint16_t n_cigar_op) const
{
std::vector<cigar> operations{};
char operation{'\0'};
uint32_t count{};
int32_t ref_length{}, seq_length{};
uint32_t operation_and_count{}; // in BAM operation and count values are stored within one 32 bit integer
constexpr char const * cigar_mapping = "MIDNSHP=X*******";
constexpr uint32_t cigar_mask = 0x0f; // 0000000000001111
if (n_cigar_op == 0) // [[unlikely]]
return std::tuple{operations, ref_length, seq_length};
// parse the rest of the cigar
// -------------------------------------------------------------------------------------------------------------
while (n_cigar_op > 0) // until stream is not empty
{
std::ranges::copy_n(std::ranges::begin(cigar_input),
sizeof(operation_and_count),
reinterpret_cast<char*>(&operation_and_count));
operation = cigar_mapping[operation_and_count & cigar_mask];
count = operation_and_count >> 4;
detail::update_alignment_lengths(ref_length, seq_length, operation, count);
operations.emplace_back(count, cigar::operation{}.assign_char(operation));
--n_cigar_op;
}
return std::tuple{operations, ref_length, seq_length};
}
/*!\brief Writes the optional fields of the seqan3::sam_tag_dictionary.
* \param[in] tag_dict The tag dictionary to print.
*/
inline std::string format_bam::get_tag_dict_str(sam_tag_dictionary const & tag_dict)
{
std::string result{};
auto stream_variant_fn = [&result] (auto && arg) // helper to print an std::variant
{
// T is either char, int32_t, float, std::string, or a std::vector<some int>
using T = std::remove_cvref_t<decltype(arg)>;
if constexpr (std::same_as<T, int32_t>)
{
// always choose the smallest possible representation [cCsSiI]
size_t const absolute_arg = std::abs(arg);
auto n = std::countr_zero(std::bit_ceil(absolute_arg + 1u) >> 1u) / 8u;
bool const negative = arg < 0;
n = n * n + 2 * negative; // for switch case order
switch (n)
{
case 0:
{
result[result.size() - 1] = 'C';
result.append(reinterpret_cast<char const *>(&arg), 1);
break;
}
case 1:
{
result[result.size() - 1] = 'S';
result.append(reinterpret_cast<char const *>(&arg), 2);
break;
}
case 2:
{
result[result.size() - 1] = 'c';
int8_t tmp = static_cast<int8_t>(arg);
result.append(reinterpret_cast<char const *>(&tmp), 1);
break;
}
case 3:
{
result[result.size() - 1] = 's';
int16_t tmp = static_cast<int16_t>(arg);
result.append(reinterpret_cast<char const *>(&tmp), 2);
break;
}
default:
{
result.append(reinterpret_cast<char const *>(&arg), 4); // always i
break;
}
}
}
else if constexpr (std::same_as<T, std::string>)
{
result.append(reinterpret_cast<char const *>(arg.data()), arg.size() + 1/*+ null character*/);
}
else if constexpr (!std::ranges::range<T>) // char, float
{
result.append(reinterpret_cast<char const *>(&arg), sizeof(arg));
}
else // std::vector of some arithmetic_type type
{
int32_t sz{static_cast<int32_t>(arg.size())};
result.append(reinterpret_cast<char *>(&sz), 4);
result.append(reinterpret_cast<char const *>(arg.data()),
arg.size() * sizeof(std::ranges::range_value_t<T>));
}
};
for (auto & [tag, variant] : tag_dict)
{
result.push_back(static_cast<char>(tag / 256));
result.push_back(static_cast<char>(tag % 256));
result.push_back(detail::sam_tag_type_char[variant.index()]);
if (!is_char<'\0'>(detail::sam_tag_type_char_extra[variant.index()]))
result.push_back(detail::sam_tag_type_char_extra[variant.index()]);
std::visit(stream_variant_fn, variant);
}
return result;
}
} // namespace seqan3
|
// Scintilla source code edit control
/** @file RESearch.cxx
** Regular expression search library.
**/
/*
* regex - Regular expression pattern matching and replacement
*
* By: Ozan S. Yigit (oz)
* Dept. of Computer Science
* York University
*
* Original code available from http://www.cs.yorku.ca/~oz/
* Translation to C++ by Neil Hodgson neilh@scintilla.org
* Removed all use of register.
* Converted to modern function prototypes.
* Put all global/static variables into an object so this code can be
* used from multiple threads, etc.
* Some extensions by Philippe Lhoste PhiLho(a)GMX.net
* '?' extensions by Michael Mullin masmullin@gmail.com
*
* These routines are the PUBLIC DOMAIN equivalents of regex
* routines as found in 4.nBSD UN*X, with minor extensions.
*
* These routines are derived from various implementations found
* in software tools books, and Conroy's grep. They are NOT derived
* from licensed/restricted software.
* For more interesting/academic/complicated implementations,
* see Henry Spencer's regexp routines, or GNU Emacs pattern
* matching module.
*
* Modification history removed.
*
* Interfaces:
* RESearch::Compile: compile a regular expression into a NFA.
*
* const char *RESearch::Compile(const char *pattern, int length,
* bool caseSensitive, bool posix)
*
* Returns a short error string if they fail.
*
* RESearch::Execute: execute the NFA to match a pattern.
*
* int RESearch::Execute(characterIndexer &ci, int lp, int endp)
*
* RESearch::Substitute: substitute the matched portions in a new string.
*
* int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst)
*
* re_fail: failure routine for RESearch::Execute. (no longer used)
*
* void re_fail(char *msg, char op)
*
* Regular Expressions:
*
* [1] char matches itself, unless it is a special
* character (metachar): . \ [ ] * + ? ^ $
* and ( ) if posix option.
*
* [2] . matches any character.
*
* [3] \ matches the character following it, except:
* - \a, \b, \f, \n, \r, \t, \v match the corresponding C
* escape char, respectively BEL, BS, FF, LF, CR, TAB and VT;
* Note that \r and \n are never matched because Scintilla
* regex searches are made line per line
* (stripped of end-of-line chars).
* - if not in posix mode, when followed by a
* left or right round bracket (see [8]);
* - when followed by a digit 1 to 9 (see [9]);
* - when followed by a left or right angle bracket
* (see [10]);
* - when followed by d, D, s, S, w or W (see [11]);
* - when followed by x and two hexa digits (see [12].
* Backslash is used as an escape character for all
* other meta-characters, and itself.
*
* [4] [set] matches one of the characters in the set.
* If the first character in the set is "^",
* it matches the characters NOT in the set, i.e.
* complements the set. A shorthand S-E (start dash end)
* is used to specify a set of characters S up to
* E, inclusive. S and E must be characters, otherwise
* the dash is taken literally (eg. in expression [\d-a]).
* The special characters "]" and "-" have no special
* meaning if they appear as the first chars in the set.
* To include both, put - first: [-]A-Z]
* (or just backslash them).
* examples: match:
*
* [-]|] matches these 3 chars,
*
* []-|] matches from ] to | chars
*
* [a-z] any lowercase alpha
*
* [^-]] any char except - and ]
*
* [^A-Z] any char except uppercase
* alpha
*
* [a-zA-Z] any alpha
*
* [5] * any regular expression form [1] to [4]
* (except [8], [9] and [10] forms of [3]),
* followed by closure char (*)
* matches zero or more matches of that form.
*
* [6] + same as [5], except it matches one or more.
*
* [5-6] Both [5] and [6] are greedy (they match as much as possible).
* Unless they are followed by the 'lazy' quantifier (?)
* In which case both [5] and [6] try to match as little as possible
*
* [7] ? same as [5] except it matches zero or one.
*
* [8] a regular expression in the form [1] to [13], enclosed
* as \(form\) (or (form) with posix flag) matches what
* form matches. The enclosure creates a set of tags,
* used for [9] and for pattern substitution.
* The tagged forms are numbered starting from 1.
*
* [9] a \ followed by a digit 1 to 9 matches whatever a
* previously tagged regular expression ([8]) matched.
*
* [10] \< a regular expression starting with a \< construct
* \> and/or ending with a \> construct, restricts the
* pattern matching to the beginning of a word, and/or
* the end of a word. A word is defined to be a character
* string beginning and/or ending with the characters
* A-Z a-z 0-9 and _. Scintilla extends this definition
* by user setting. The word must also be preceded and/or
* followed by any character outside those mentioned.
*
* [11] \l a backslash followed by d, D, s, S, w or W,
* becomes a character class (both inside and
* outside sets []).
* d: decimal digits
* D: any char except decimal digits
* s: whitespace (space, \t \n \r \f \v)
* S: any char except whitespace (see above)
* w: alphanumeric & underscore (changed by user setting)
* W: any char except alphanumeric & underscore (see above)
*
* [12] \xHH a backslash followed by x and two hexa digits,
* becomes the character whose Ascii code is equal
* to these digits. If not followed by two digits,
* it is 'x' char itself.
*
* [13] a composite regular expression xy where x and y
* are in the form [1] to [12] matches the longest
* match of x followed by a match for y.
*
* [14] ^ a regular expression starting with a ^ character
* $ and/or ending with a $ character, restricts the
* pattern matching to the beginning of the line,
* or the end of line. [anchors] Elsewhere in the
* pattern, ^ and $ are treated as ordinary characters.
*
*
* Acknowledgements:
*
* HCR's Hugh Redelmeier has been most helpful in various
* stages of development. He convinced me to include BOW
* and EOW constructs, originally invented by Rob Pike at
* the University of Toronto.
*
* References:
* Software tools Kernighan & Plauger
* Software tools in Pascal Kernighan & Plauger
* Grep [rsx-11 C dist] David Conroy
* ed - text editor Un*x Programmer's Manual
* Advanced editing on Un*x B. W. Kernighan
* RegExp routines Henry Spencer
*
* Notes:
*
* This implementation uses a bit-set representation for character
* classes for speed and compactness. Each character is represented
* by one bit in a 256-bit block. Thus, CCL always takes a
* constant 32 bytes in the internal nfa, and RESearch::Execute does a single
* bit comparison to locate the character in the set.
*
* Examples:
*
* pattern: foo*.*
* compile: CHR f CHR o CLO CHR o END CLO ANY END END
* matches: fo foo fooo foobar fobar foxx ...
*
* pattern: fo[ob]a[rz]
* compile: CHR f CHR o CCL bitset CHR a CCL bitset END
* matches: fobar fooar fobaz fooaz
*
* pattern: foo\\+
* compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END
* matches: foo\ foo\\ foo\\\ ...
*
* pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo)
* compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END
* matches: foo1foo foo2foo foo3foo
*
* pattern: \(fo.*\)-\1
* compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END
* matches: foo-foo fo-fo fob-fob foobar-foobar ...
*/
#include <stdlib.h>
#include "CharClassify.h"
#include "RESearch.h"
// Shut up annoying Visual C++ warnings:
#ifdef _MSC_VER
#pragma warning(disable: 4514)
#endif
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
#define OKP 1
#define NOP 0
#define CHR 1
#define ANY 2
#define CCL 3
#define BOL 4
#define EOL 5
#define BOT 6
#define EOT 7
#define BOW 8
#define EOW 9
#define REF 10
#define CLO 11
#define CLQ 12 /* 0 to 1 closure */
#define LCLO 13 /* lazy closure */
#define END 0
/*
* The following defines are not meant to be changeable.
* They are for readability only.
*/
#define BLKIND 0370
#define BITIND 07
const char bitarr[] = { 1, 2, 4, 8, 16, 32, 64, '\200' };
#define badpat(x) (*nfa = END, x)
/*
* Character classification table for word boundary operators BOW
* and EOW is passed in by the creator of this object (Scintilla
* Document). The Document default state is that word chars are:
* 0-9, a-z, A-Z and _
*/
RESearch::RESearch(CharClassify *charClassTable) {
failure = 0;
charClass = charClassTable;
Init();
}
RESearch::~RESearch() {
Clear();
}
void RESearch::Init() {
sta = NOP; /* status of lastpat */
bol = 0;
for (int i = 0; i < MAXTAG; i++)
pat[i] = 0;
for (int j = 0; j < BITBLK; j++)
bittab[j] = 0;
}
void RESearch::Clear() {
for (int i = 0; i < MAXTAG; i++) {
delete []pat[i];
pat[i] = 0;
bopat[i] = NOTFOUND;
eopat[i] = NOTFOUND;
}
}
bool RESearch::GrabMatches(CharacterIndexer &ci) {
bool success = true;
for (unsigned int i = 0; i < MAXTAG; i++) {
if ((bopat[i] != NOTFOUND) && (eopat[i] != NOTFOUND)) {
unsigned int len = eopat[i] - bopat[i];
pat[i] = new char[len + 1];
if (pat[i]) {
for (unsigned int j = 0; j < len; j++)
pat[i][j] = ci.CharAt(bopat[i] + j);
pat[i][len] = '\0';
} else {
success = false;
}
}
}
return success;
}
void RESearch::ChSet(unsigned char c) {
bittab[((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND];
}
void RESearch::ChSetWithCase(unsigned char c, bool caseSensitive) {
if (caseSensitive) {
ChSet(c);
} else {
if ((c >= 'a') && (c <= 'z')) {
ChSet(c);
ChSet(static_cast<unsigned char>(c - 'a' + 'A'));
} else if ((c >= 'A') && (c <= 'Z')) {
ChSet(c);
ChSet(static_cast<unsigned char>(c - 'A' + 'a'));
} else {
ChSet(c);
}
}
}
unsigned char escapeValue(unsigned char ch) {
switch (ch) {
case 'a': return '\a';
case 'b': return '\b';
case 'f': return '\f';
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
case 'v': return '\v';
}
return 0;
}
static int GetHexaChar(unsigned char hd1, unsigned char hd2) {
int hexValue = 0;
if (hd1 >= '0' && hd1 <= '9') {
hexValue += 16 * (hd1 - '0');
} else if (hd1 >= 'A' && hd1 <= 'F') {
hexValue += 16 * (hd1 - 'A' + 10);
} else if (hd1 >= 'a' && hd1 <= 'f') {
hexValue += 16 * (hd1 - 'a' + 10);
} else
return -1;
if (hd2 >= '0' && hd2 <= '9') {
hexValue += hd2 - '0';
} else if (hd2 >= 'A' && hd2 <= 'F') {
hexValue += hd2 - 'A' + 10;
} else if (hd2 >= 'a' && hd2 <= 'f') {
hexValue += hd2 - 'a' + 10;
} else
return -1;
return hexValue;
}
/**
* Called when the parser finds a backslash not followed
* by a valid expression (like \( in non-Posix mode).
* @param pattern: pointer on the char after the backslash.
* @param incr: (out) number of chars to skip after expression evaluation.
* @return the char if it resolves to a simple char,
* or -1 for a char class. In this case, bittab is changed.
*/
int RESearch::GetBackslashExpression(
const char *pattern,
int &incr) {
// Since error reporting is primitive and messages are not used anyway,
// I choose to interpret unexpected syntax in a logical way instead
// of reporting errors. Otherwise, we can stick on, eg., PCRE behavior.
incr = 0; // Most of the time, will skip the char "naturally".
int c;
int result = -1;
unsigned char bsc = *pattern;
if (!bsc) {
// Avoid overrun
result = '\\'; // \ at end of pattern, take it literally
return result;
}
switch (bsc) {
case 'a':
case 'b':
case 'n':
case 'f':
case 'r':
case 't':
case 'v':
result = escapeValue(bsc);
break;
case 'x': {
unsigned char hd1 = *(pattern + 1);
unsigned char hd2 = *(pattern + 2);
int hexValue = GetHexaChar(hd1, hd2);
if (hexValue >= 0) {
result = hexValue;
incr = 2; // Must skip the digits
} else {
result = 'x'; // \x without 2 digits: see it as 'x'
}
}
break;
case 'd':
for (c = '0'; c <= '9'; c++) {
ChSet(static_cast<unsigned char>(c));
}
break;
case 'D':
for (c = 0; c < MAXCHR; c++) {
if (c < '0' || c > '9') {
ChSet(static_cast<unsigned char>(c));
}
}
break;
case 's':
ChSet(' ');
ChSet('\t');
ChSet('\n');
ChSet('\r');
ChSet('\f');
ChSet('\v');
break;
case 'S':
for (c = 0; c < MAXCHR; c++) {
if (c != ' ' && !(c >= 0x09 && c <= 0x0D)) {
ChSet(static_cast<unsigned char>(c));
}
}
break;
case 'w':
for (c = 0; c < MAXCHR; c++) {
if (iswordc(static_cast<unsigned char>(c))) {
ChSet(static_cast<unsigned char>(c));
}
}
break;
case 'W':
for (c = 0; c < MAXCHR; c++) {
if (!iswordc(static_cast<unsigned char>(c))) {
ChSet(static_cast<unsigned char>(c));
}
}
break;
default:
result = bsc;
}
return result;
}
const char *RESearch::Compile(const char *pattern, int length, bool caseSensitive, bool posix) {
char *mp=nfa; /* nfa pointer */
char *lp; /* saved pointer */
char *sp=nfa; /* another one */
char *mpMax = mp + MAXNFA - BITBLK - 10;
int tagi = 0; /* tag stack index */
int tagc = 1; /* actual tag count */
int n;
char mask; /* xor mask -CCL/NCL */
int c1, c2, prevChar;
if (!pattern || !length) {
if (sta)
return 0;
else
return badpat("No previous regular expression");
}
sta = NOP;
const char *p=pattern; /* pattern pointer */
for (int i=0; i<length; i++, p++) {
if (mp > mpMax)
return badpat("Pattern too long");
lp = mp;
switch (*p) {
case '.': /* match any char */
*mp++ = ANY;
break;
case '^': /* match beginning */
if (p == pattern)
*mp++ = BOL;
else {
*mp++ = CHR;
*mp++ = *p;
}
break;
case '$': /* match endofline */
if (!*(p+1))
*mp++ = EOL;
else {
*mp++ = CHR;
*mp++ = *p;
}
break;
case '[': /* match char class */
*mp++ = CCL;
prevChar = 0;
i++;
if (*++p == '^') {
mask = '\377';
i++;
p++;
} else
mask = 0;
if (*p == '-') { /* real dash */
i++;
prevChar = *p;
ChSet(*p++);
}
if (*p == ']') { /* real brace */
i++;
prevChar = *p;
ChSet(*p++);
}
while (*p && *p != ']') {
if (*p == '-') {
if (prevChar < 0) {
// Previous def. was a char class like \d, take dash literally
prevChar = *p;
ChSet(*p);
} else if (*(p+1)) {
if (*(p+1) != ']') {
c1 = prevChar + 1;
i++;
c2 = static_cast<unsigned char>(*++p);
if (c2 == '\\') {
if (!*(p+1)) // End of RE
return badpat("Missing ]");
else {
i++;
p++;
int incr;
c2 = GetBackslashExpression(p, incr);
i += incr;
p += incr;
if (c2 >= 0) {
// Convention: \c (c is any char) is case sensitive, whatever the option
ChSet(static_cast<unsigned char>(c2));
prevChar = c2;
} else {
// bittab is already changed
prevChar = -1;
}
}
}
if (prevChar < 0) {
// Char after dash is char class like \d, take dash literally
prevChar = '-';
ChSet('-');
} else {
// Put all chars between c1 and c2 included in the char set
while (c1 <= c2) {
ChSetWithCase(static_cast<unsigned char>(c1++), caseSensitive);
}
}
} else {
// Dash before the ], take it literally
prevChar = *p;
ChSet(*p);
}
} else {
return badpat("Missing ]");
}
} else if (*p == '\\' && *(p+1)) {
i++;
p++;
int incr;
int c = GetBackslashExpression(p, incr);
i += incr;
p += incr;
if (c >= 0) {
// Convention: \c (c is any char) is case sensitive, whatever the option
ChSet(static_cast<unsigned char>(c));
prevChar = c;
} else {
// bittab is already changed
prevChar = -1;
}
} else {
prevChar = static_cast<unsigned char>(*p);
ChSetWithCase(*p, caseSensitive);
}
i++;
p++;
}
if (!*p)
return badpat("Missing ]");
for (n = 0; n < BITBLK; bittab[n++] = 0)
*mp++ = static_cast<char>(mask ^ bittab[n]);
break;
case '*': /* match 0 or more... */
case '+': /* match 1 or more... */
case '?':
if (p == pattern)
return badpat("Empty closure");
lp = sp; /* previous opcode */
if (*lp == CLO || *lp == LCLO) /* equivalence... */
break;
switch (*lp) {
case BOL:
case BOT:
case EOT:
case BOW:
case EOW:
case REF:
return badpat("Illegal closure");
default:
break;
}
if (*p == '+')
for (sp = mp; lp < sp; lp++)
*mp++ = *lp;
*mp++ = END;
*mp++ = END;
sp = mp;
while (--mp > lp)
*mp = mp[-1];
if (*p == '?') *mp = CLQ;
else if (*(p+1) == '?') *mp = LCLO;
else *mp = CLO;
mp = sp;
break;
case '\\': /* tags, backrefs... */
i++;
switch (*++p) {
case '<':
*mp++ = BOW;
break;
case '>':
if (*sp == BOW)
return badpat("Null pattern inside \\<\\>");
*mp++ = EOW;
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
n = *p-'0';
if (tagi > 0 && tagstk[tagi] == n)
return badpat("Cyclical reference");
if (tagc > n) {
*mp++ = static_cast<char>(REF);
*mp++ = static_cast<char>(n);
} else
return badpat("Undetermined reference");
break;
default:
if (!posix && *p == '(') {
if (tagc < MAXTAG) {
tagstk[++tagi] = tagc;
*mp++ = BOT;
*mp++ = static_cast<char>(tagc++);
} else
return badpat("Too many \\(\\) pairs");
} else if (!posix && *p == ')') {
if (*sp == BOT)
return badpat("Null pattern inside \\(\\)");
if (tagi > 0) {
*mp++ = static_cast<char>(EOT);
*mp++ = static_cast<char>(tagstk[tagi--]);
} else
return badpat("Unmatched \\)");
} else {
int incr;
int c = GetBackslashExpression(p, incr);
i += incr;
p += incr;
if (c >= 0) {
*mp++ = CHR;
*mp++ = static_cast<unsigned char>(c);
} else {
*mp++ = CCL;
mask = 0;
for (n = 0; n < BITBLK; bittab[n++] = 0)
*mp++ = static_cast<char>(mask ^ bittab[n]);
}
}
}
break;
default : /* an ordinary char */
if (posix && *p == '(') {
if (tagc < MAXTAG) {
tagstk[++tagi] = tagc;
*mp++ = BOT;
*mp++ = static_cast<char>(tagc++);
} else
return badpat("Too many () pairs");
} else if (posix && *p == ')') {
if (*sp == BOT)
return badpat("Null pattern inside ()");
if (tagi > 0) {
*mp++ = static_cast<char>(EOT);
*mp++ = static_cast<char>(tagstk[tagi--]);
} else
return badpat("Unmatched )");
} else {
unsigned char c = *p;
if (!c) // End of RE
c = '\\'; // We take it as raw backslash
if (caseSensitive || !iswordc(c)) {
*mp++ = CHR;
*mp++ = c;
} else {
*mp++ = CCL;
mask = 0;
ChSetWithCase(c, false);
for (n = 0; n < BITBLK; bittab[n++] = 0)
*mp++ = static_cast<char>(mask ^ bittab[n]);
}
}
break;
}
sp = lp;
}
if (tagi > 0)
return badpat((posix ? "Unmatched (" : "Unmatched \\("));
*mp = END;
sta = OKP;
return 0;
}
/*
* RESearch::Execute:
* execute nfa to find a match.
*
* special cases: (nfa[0])
* BOL
* Match only once, starting from the
* beginning.
* CHR
* First locate the character without
* calling PMatch, and if found, call
* PMatch for the remaining string.
* END
* RESearch::Compile failed, poor luser did not
* check for it. Fail fast.
*
* If a match is found, bopat[0] and eopat[0] are set
* to the beginning and the end of the matched fragment,
* respectively.
*
*/
int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) {
unsigned char c;
int ep = NOTFOUND;
char *ap = nfa;
bol = lp;
failure = 0;
Clear();
switch (*ap) {
case BOL: /* anchored: match from BOL only */
ep = PMatch(ci, lp, endp, ap);
break;
case EOL: /* just searching for end of line normal path doesn't work */
if (*(ap+1) == END) {
lp = endp;
ep = lp;
break;
} else {
return 0;
}
case CHR: /* ordinary char: locate it fast */
c = *(ap+1);
while ((lp < endp) && (ci.CharAt(lp) != c))
lp++;
if (lp >= endp) /* if EOS, fail, else fall thru. */
return 0;
default: /* regular matching all the way. */
while (lp < endp) {
ep = PMatch(ci, lp, endp, ap);
if (ep != NOTFOUND)
break;
lp++;
}
break;
case END: /* munged automaton. fail always */
return 0;
}
if (ep == NOTFOUND)
return 0;
bopat[0] = lp;
eopat[0] = ep;
return 1;
}
/*
* PMatch: internal routine for the hard part
*
* This code is partly snarfed from an early grep written by
* David Conroy. The backref and tag stuff, and various other
* innovations are by oz.
*
* special case optimizations: (nfa[n], nfa[n+1])
* CLO ANY
* We KNOW .* will match everything upto the
* end of line. Thus, directly go to the end of
* line, without recursive PMatch calls. As in
* the other closure cases, the remaining pattern
* must be matched by moving backwards on the
* string recursively, to find a match for xy
* (x is ".*" and y is the remaining pattern)
* where the match satisfies the LONGEST match for
* x followed by a match for y.
* CLO CHR
* We can again scan the string forward for the
* single char and at the point of failure, we
* execute the remaining nfa recursively, same as
* above.
*
* At the end of a successful match, bopat[n] and eopat[n]
* are set to the beginning and end of subpatterns matched
* by tagged expressions (n = 1 to 9).
*/
extern void re_fail(char *,char);
#define isinset(x,y) ((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND])
/*
* skip values for CLO XXX to skip past the closure
*/
#define ANYSKIP 2 /* [CLO] ANY END */
#define CHRSKIP 3 /* [CLO] CHR chr END */
#define CCLSKIP 34 /* [CLO] CCL 32 bytes END */
int RESearch::PMatch(CharacterIndexer &ci, int lp, int endp, char *ap) {
int op, c, n;
int e; /* extra pointer for CLO */
int bp; /* beginning of subpat... */
int ep; /* ending of subpat... */
int are; /* to save the line ptr. */
int llp; /* lazy lp for LCLO */
while ((op = *ap++) != END)
switch (op) {
case CHR:
if (ci.CharAt(lp++) != *ap++)
return NOTFOUND;
break;
case ANY:
if (lp++ >= endp)
return NOTFOUND;
break;
case CCL:
if (lp >= endp)
return NOTFOUND;
c = ci.CharAt(lp++);
if (!isinset(ap,c))
return NOTFOUND;
ap += BITBLK;
break;
case BOL:
if (lp != bol)
return NOTFOUND;
break;
case EOL:
if (lp < endp)
return NOTFOUND;
break;
case BOT:
bopat[static_cast<int>(*ap++)] = lp;
break;
case EOT:
eopat[static_cast<int>(*ap++)] = lp;
break;
case BOW:
if ((lp!=bol && iswordc(ci.CharAt(lp-1))) || !iswordc(ci.CharAt(lp)))
return NOTFOUND;
break;
case EOW:
if (lp==bol || !iswordc(ci.CharAt(lp-1)) || iswordc(ci.CharAt(lp)))
return NOTFOUND;
break;
case REF:
n = *ap++;
bp = bopat[n];
ep = eopat[n];
while (bp < ep)
if (ci.CharAt(bp++) != ci.CharAt(lp++))
return NOTFOUND;
break;
case LCLO:
case CLQ:
case CLO:
are = lp;
switch (*ap) {
case ANY:
if (op == CLO || op == LCLO)
while (lp < endp)
lp++;
else if (lp < endp)
lp++;
n = ANYSKIP;
break;
case CHR:
c = *(ap+1);
if (op == CLO || op == LCLO)
while ((lp < endp) && (c == ci.CharAt(lp)))
lp++;
else if ((lp < endp) && (c == ci.CharAt(lp)))
lp++;
n = CHRSKIP;
break;
case CCL:
while ((lp < endp) && isinset(ap+1,ci.CharAt(lp)))
lp++;
n = CCLSKIP;
break;
default:
failure = true;
//re_fail("closure: bad nfa.", *ap);
return NOTFOUND;
}
ap += n;
llp = lp;
e = NOTFOUND;
while (llp >= are) {
int q;
if ((q = PMatch(ci, llp, endp, ap)) != NOTFOUND) {
e = q;
lp = llp;
if (op != LCLO) return e;
}
if (*ap == END) return e;
--llp;
}
if (*ap == EOT)
PMatch(ci, lp, endp, ap);
return e;
default:
//re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op));
return NOTFOUND;
}
return lp;
}
/*
* RESearch::Substitute:
* substitute the matched portions of the src in dst.
*
* & substitute the entire matched pattern.
*
* \digit substitute a subpattern, with the given tag number.
* Tags are numbered from 1 to 9. If the particular
* tagged subpattern does not exist, null is substituted.
*/
int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst) {
unsigned char c;
int pin;
int bp;
int ep;
if (!*src || !bopat[0])
return 0;
while ((c = *src++) != 0) {
switch (c) {
case '&':
pin = 0;
break;
case '\\':
c = *src++;
if (c >= '0' && c <= '9') {
pin = c - '0';
break;
}
default:
*dst++ = c;
continue;
}
if ((bp = bopat[pin]) != 0 && (ep = eopat[pin]) != 0) {
while (ci.CharAt(bp) && bp < ep)
*dst++ = ci.CharAt(bp++);
if (bp < ep)
return 0;
}
}
*dst = '\0';
return 1;
}
|
.data # Program at 1.1
.byte 10 # StringLiteral at 6.12
.byte 0 # StringLiteral at 6.12
.byte 0 # StringLiteral at 6.12
.byte 0 # StringLiteral at 6.12
.word CLASS_String # StringLiteral at 6.12
.word 2 # StringLiteral at 6.12
.word -1 # StringLiteral at 6.12
strLit_16: # StringLiteral at 6.12
# ENTER NODE # Program at 1.1
.text # Program at 1.1
.globl main # Program at 1.1
main: # Program at 1.1
#initialize registers, etc. # Program at 1.1
jal vm_init # Program at 1.1
# ENTER NODE # CallStatement at 0.0
# ENTER NODE # Call at 0.0
# ENTER NODE # NewObject at 0.0
subu $sp, $sp, 4 # NewObject at 0.0
sw $zero, ($sp) # NewObject at 0.0
# EXIT NODE # NewObject at 0.0
lw $t0, -4($sp) # Call at 0.0
beq $t0, $zero, nullPtrException # Call at 0.0
lw $t0, -12($t0) # Call at 0.0
lw $t0, 0($t0) # Call at 0.0
jalr $t0 # Call at 0.0
# EXIT NODE # Call at 0.0
# EXIT NODE # CallStatement at 0.0
CLASS_String: # Program at 1.1
CLASS_Object: # Program at 1.1
#exit program # Program at 1.1
li $v0, 10 # Program at 1.1
syscall # Program at 1.1
# ENTER NODE # MethodDeclVoid at 2.14
.globl fcn_20_main # MethodDeclVoid at 2.14
fcn_20_main: # MethodDeclVoid at 2.14
subu $sp,$sp,4 # MethodDeclVoid at 2.14
sw $s2,($sp) # MethodDeclVoid at 2.14
lw $s2, 0($sp) # MethodDeclVoid at 2.14
sw $ra, 0($sp) # MethodDeclVoid at 2.14
# ENTER NODE # LocalVarDecl at 3.7
# ENTER NODE # IntegerLiteral at 3.13
subu $sp, $sp, 8 # IntegerLiteral at 3.13
sw $s5, 4($sp) # IntegerLiteral at 3.13
li $t0, 176 # IntegerLiteral at 3.13
sw $t0, ($sp) # IntegerLiteral at 3.13
# EXIT NODE # IntegerLiteral at 3.13
# EXIT NODE # LocalVarDecl at 3.7
# ENTER NODE # LocalVarDecl at 4.7
# ENTER NODE # Plus at 4.16
# ENTER NODE # IdentifierExp at 4.13
lw $t0, 0($sp) # IdentifierExp at 4.13
subu $sp, $sp, 8 # IdentifierExp at 4.13
sw $s5, 4($sp) # IdentifierExp at 4.13
sw $t0, ($sp) # IdentifierExp at 4.13
# EXIT NODE # IdentifierExp at 4.13
# ENTER NODE # IntegerLiteral at 4.17
subu $sp, $sp, 8 # IntegerLiteral at 4.17
sw $s5, 4($sp) # IntegerLiteral at 4.17
li $t0, 30 # IntegerLiteral at 4.17
sw $t0, ($sp) # IntegerLiteral at 4.17
# EXIT NODE # IntegerLiteral at 4.17
lw $t0, ($sp) # Plus at 4.16
lw $t1, 8($sp) # Plus at 4.16
addu $t0, $t0, $t1 # Plus at 4.16
addu $sp, $sp, 8 # Plus at 4.16
sw $t0, ($sp) # Plus at 4.16
# EXIT NODE # Plus at 4.16
# EXIT NODE # LocalVarDecl at 4.7
# ENTER NODE # CallStatement at 5.3
# ENTER NODE # Call at 5.3
# ENTER NODE # This at 5.3
subu $sp, $sp, 4 # This at 5.3
sw $s2, ($sp) # This at 5.3
# EXIT NODE # This at 5.3
# ENTER NODE # Plus at 5.15
# ENTER NODE # IdentifierExp at 5.12
lw $t0, 4($sp) # IdentifierExp at 5.12
subu $sp, $sp, 8 # IdentifierExp at 5.12
sw $s5, 4($sp) # IdentifierExp at 5.12
sw $t0, ($sp) # IdentifierExp at 5.12
# EXIT NODE # IdentifierExp at 5.12
# ENTER NODE # IntegerLiteral at 5.16
subu $sp, $sp, 8 # IntegerLiteral at 5.16
sw $s5, 4($sp) # IntegerLiteral at 5.16
li $t0, 6 # IntegerLiteral at 5.16
sw $t0, ($sp) # IntegerLiteral at 5.16
# EXIT NODE # IntegerLiteral at 5.16
lw $t0, ($sp) # Plus at 5.15
lw $t1, 8($sp) # Plus at 5.15
addu $t0, $t0, $t1 # Plus at 5.15
addu $sp, $sp, 8 # Plus at 5.15
sw $t0, ($sp) # Plus at 5.15
# EXIT NODE # Plus at 5.15
lw $t0, -4($sp) # Call at 5.3
beq $t0, $zero, nullPtrException # Call at 5.3
lw $t0, -12($t0) # Call at 5.3
lw $t0, 0($t0) # Call at 5.3
jalr $t0 # Call at 5.3
# EXIT NODE # Call at 5.3
# EXIT NODE # CallStatement at 5.3
# ENTER NODE # CallStatement at 6.3
# ENTER NODE # Call at 6.3
# ENTER NODE # This at 6.3
subu $sp, $sp, 4 # This at 6.3
sw $s2, ($sp) # This at 6.3
# EXIT NODE # This at 6.3
# ENTER NODE # StringLiteral at 6.12
subu $sp, $sp, 4 # StringLiteral at 6.12
la $t0, strLit_16 # StringLiteral at 6.12
sw $t0, ($sp) # StringLiteral at 6.12
# EXIT NODE # StringLiteral at 6.12
lw $t0, -4($sp) # Call at 6.3
beq $t0, $zero, nullPtrException # Call at 6.3
lw $t0, -12($t0) # Call at 6.3
lw $t0, 0($t0) # Call at 6.3
jalr $t0 # Call at 6.3
# EXIT NODE # Call at 6.3
# EXIT NODE # CallStatement at 6.3
lw $ra,16($sp) # MethodDeclVoid at 2.14
lw $s2,16($sp) # MethodDeclVoid at 2.14
addu $sp,$sp,24 # MethodDeclVoid at 2.14
jr $ra # MethodDeclVoid at 2.14
# EXIT NODE # MethodDeclVoid at 2.14
##############################################################
# MiniJava/UP library for MIPS/Spim -- version that assumes
# one-word boolean on stack
# author: Steven R. Vegdahl
# date: 7-13 July 2004
# modified 12-17 March 2007
# modified 3-25 May 2007
# modified 2 May 2015
# modified 7 March 2016
# status: reasonably debugged (allegedly)
###############################################################
.text
###############################################################
# equals() - library method (class Object)
# - tests whether two objects are equal
# - produces boolean that tells whether two objects are equal--
# meaning that they are the same physical object
# - parameters:
# - ($sp) - this-pointer
# - 4($sp) - object to compare to
# - return-value:
# - ($sp) - 1 if the objects were the same; 0 otherwise
###############################################################
equals_Object:
lw $t0,($sp) # second pointer
lw $t1,4($sp) # first pointer (this)
seq $t0,$t0,$t1 # produce boolean telling if they are equal
addu $sp,4 # adjust stack
sw $t0,($sp) # store return value on top of stack
jr $ra # return
###############################################################
# equals() - library method (class String)
# - the String version of the .equals method
# - produces false if the second object is null or is not a String ;
# otherwise produces true iff the two strings have the same contents
# - parameters:
# - ($sp) - this-pointer
# - 4($sp) - object to compare to
# - return-value:
# - ($sp) - 1 if the objects were the same; 0 otherwise
###############################################################
equals_String:
# quick test for obvious false
lw $t0,($sp) # second parameter
beq $t0,$zero,goEsFalse # go return false if null
lw $t1,-12($t0) # vtable pointer
la $t2,CLASS_String # string vtable pointer
bne $t1,$t2,goEsFalse # go return false if not a string
# save $ra, $sp, etc
subu $sp,12
sw $s2,8($sp)
lw $s2,16($sp)
sw $ra,16($sp)
# call "compareTo"
sw $s2,4($sp)
sw $t0,($sp)
jal compareTo_String
# return value is 1 iff result is 0; else 0
lw $t0,($sp)
seq $t0,$t0,$zero
# unwind stack and return
lw $s2,8($sp)
lw $ra,16($sp)
sw $t0,16($sp) # return value
addu $sp,16
jr $ra # return
goEsFalse:
addu $sp,4 # adjust stack
sw $zero,($sp) # store value
jr $ra # return
lw $t0,($sp) # second pointer
lw $t1,4($sp) # first pointer (this)
seq $t0,$t0,$t1 # produce boolean telling if they are equal
addu $sp,4 # adjust stack
sw $t0,($sp) # store return value on top of stack
jr $ra # return
###############################################################
# readLine() - library method (class Lib)
# - reads line from standard input
# - produces String that contains the line read, except that it
# does not include the end-of-line character-sequence. An
# end-of-line character-sequence is one of the following:
# - a return character followed by a newline character
# - a newline character not preceded by a return character
# - a return character not followed by a newline character
# - an end-of-file character that follows at least one data
# character
# - returns null on end-of-file
# - parameter:
# - ($sp) - this-pointer
# - return-value:
# - ($sp) - pointer to string containing line that was read
# - anomalies:
# - with bare "return", looks ahead one character to check for
# newline. This could cause non-intuitive behavior when
# run interactively.
###############################################################
readLine_Lib:
subu $sp,$sp,8 # allocate space for data tag, saving $ra
sw $ra, 4($sp) # save $ra
move $t1,$sp # save "original" sp
doRead:
# read the character
jal readLogicalChar
# if we have a 'return', read another character to check for
# newline
subu $t2,$v0,13
bne $t2,$zero,notReturnRL
jal readLogicalChar
subu $t2,$v0,10 # check for newline
beq $t2,$zero,foundNewLine
sw $v0,lastCharRead # push back character into queue
j foundNewLine # go process the line
notReturnRL:
# at this point, $v0 has our character
subu $t0,$v0,10
beq $t0,$zero,foundNewLine
blt $v0,$zero,foundEof
# we have a character, so push it onto stack
subu $sp,$sp,4
sw $v0,($sp)
# loop back up to get next character
j doRead
foundEof:
# if we had actually read some characters before hitting
# the eof, go return them as if a newline had been read
bne $t1,$sp foundNewLine
# otherwise, we got end of file without having read any
# new characters, so return null
sw $zero,8($sp) # return-value: null
j rlReturn # return
foundNewLine:
# at this point, we have our newline (or end-of-file), and all space
# on the stack above $t1 are characters to be put into the string.
# That is therefore the number of data words to allocate (plus 1
# more for the class-pointer)
# set up GC tag and char-count on stack
subu $t0,$t1,$sp # number of chars we read (times 4)
srl $s6,$t0,2 # number of words on stack with chars
subu $sp,$sp,4 # push char-count ...
sw $s6,($sp) # ... onto stack
addu $t2,$t0,5 # GC tag, incl. for count-word
sw $t2,($t1) # store GC tag
# allocate the appropriate Object
addu $s6,$s6,7 # 3 to round up, plus 1 for v-table pointer word
srl $s6,$s6,2 # data words in object
move $s7,$zero # # object words in object
jal newObject # allocate space
# store header words
la $t0,CLASS_String
sw $t0,-12($s7) # store class tag (String) into object
lw $t2,4($sp) # char-count
sll $t1,$t2,2 # 4 times number of chars
subu $t2,$zero,$t2 # negative of char-count
sw $t2,-4($s7) # store negative char-count as header-word 2
# set up pointers to various parts of stack and object
lw $t0,-8($s7) # data words in object
sll $t0,$t0,2 # data bytes in object
subu $t0,$s7,$t0 # place to store first character (plus 8)
subu $t0,$t0,$t2 # place to store last character (plus 9)
addu $sp,$sp,8 # pop redundant object-pointer and count
addu $t1,$t1,$sp # first non-char spot on stack
# at this point:
# $t0 points to the target-spot for the last character (plus 9)
# $t1 contains top spot on the stack not containing a char
# $sp points to the word with the last source character
# copy the characters, popping each off the stack
beq $sp,$t1,doneCharCopy
charCopyLoop:
lw $t2,($sp)
sb $t2,-9($t0)
addu $sp,$sp,4
subu $t0,$t0,1
bne $sp,$t1,charCopyLoop
doneCharCopy:
# put our pointer (the return value) on the eventual top stack
sw $s7,8($sp)
rlReturn:
# restore return address and return
lw $ra,4($sp) # restore return address, ...
addu $sp,$sp,8 # ... by popping it (and this-pointer) off stack
jr $ra
###################################################################
# readInt() - library method (class Lib)
# - skips whitespace
# - then attempts to read a base-10 integer from standard input
# - aborts program if a valid integer is not found
# - returns the integer that is read
# - truncates on overflow
# - parameter:
# - ($sp) - this-pointer
# - return-value:
# - ($sp) - value that was read
# - 4($sp) - (dummy) GC tag
###################################################################
readInt_Lib:
# save $ra by pushing onto stack
subu $sp,$sp,4
sw $ra,($sp)
riSkipWhiteLoop:
# read a character
jal readLogicalChar
# if character <= 32 ascii, check for whitespace; if not
# whitespace, abort
subu $t0,$v0,32
bgt $t0,$zero,nonWhite
beq $t0,$zero,riSkipWhiteLoop # start over if space
subu $t0,$v0,10
beq $t0,$zero,riSkipWhiteLoop # start over if newline
subu $t0,$v0,9
beq $t0,$zero,riSkipWhiteLoop # start over if tab
subu $t0,$v0,13
beq $t0,$zero,riSkipWhiteLoop # start over if carriage return
subu $t0,$v0,12
beq $t0,$zero,riSkipWhiteLoop # start over if form-feed
j badIntegerFormat # illegal integer char: abort program
nonWhite:
subu $t0,$v0,'-'
li $t4,1 # final multiplier
bne $t0,$zero,helpReadInt # go read
li $t4,-1 # -1 in final multiplier
# read another character to make up for the '-'
jal readLogicalChar
helpReadInt:
li $t2,10
subu $t1,$v0,'0' # convert digit to 0-9 value
bgeu $t1,$t2,badIntegerFormat # abort if not digit
move $t3,$t1 #
#### at this point, $t3 contains value of the first digit read,
#### and $t2 contains the value 10
digitLoop:
# loop invariants:
# - $t3 contains the value of the number we've read so far
# - $t2 contains the value 10
jal readLogicalChar # read next character
subu $t1,$v0,'0' # convert digit to 0-9 value
bgeu $t1,$t2,doneDigitLoop # abort if not digit
mul $t3,$t3,$t2 # multiply old value by 10
addu $t3,$t3,$t1 # add in value of new digit
j digitLoop
doneDigitLoop:
# "push back" unused character into queue
sw $v0,lastCharRead
# restore return address and overwrite it with return-val;
# write dummy GC tag as second word of return-val
lw $ra,($sp)
mult $t3,$t4 # multiply to account for poss. minus sign
mflo $t3
sw $t3,($sp) # result
sw $s5,4($sp) # dummy GC tag
#lw $zero,4($sp)#**"" #--FOR MEMORY TAGGING
# return
jr $ra
###################################################################
# readChar() - library method (class Lib)
# - reads a single character from standard input
# - returns the integer that is the encoding of the character
# - returns -1 if end of file was encountered
# - parameter:
# - ($sp) - this-pointer
# - return-value:
# - ($sp) - value that was read
# - 4($sp) - (dummy) GC tag
###################################################################
readChar_Lib:
# save $ra by pushing onto stack
subu $sp,$sp,4
sw $ra,($sp)
# read the character
jal readLogicalChar
# restore return address; put value (and dummy GC tag),
# replacing this-pointer saved return address
lw $ra,($sp)
sw $s5,4($sp)
#lw $zero,4($sp)#**"" #--FOR MEMORY TAGGING
sw $v0,($sp)
# return
jr $ra
########################################################
# printStr(str) - library method (class Lib)
# - prints string to standard output
# parameters:
# - ($sp) - the string to print
# - 4($sp) - this-pointer
########################################################
printStr_Lib:
# check for null, printing "(null)", if so
lw $t0,($sp)
bne $t0,$zero,psNotNull
# print "(null)"
la $a0,nullStr
li $v0,4
syscall
j donePrintStr
psNotNull:
##### we have a non-null string #####
# this means that:
# - number of data words in object is in -8($t0)
# - negative of number of characters in string is in -4($t0)
# - string begins at $t0-8-(#dataWords*4), stored 1 char per byte
subu $t0,$t0,8
lw $t1,($t0) # word just beyond end of string
sll $t1,$t1,2
subu $t1,$t0,$t1 # first word in string
lw $t0,4($t0) # negative of string-length
subu $t0,$t1,$t0 # byte just beyond last char in string
# print the chars in the string
beq $t0,$t1,donePrintStr
psLoop:
lb $a0,($t1) # next byte
li $v0,11 # code for printing char
syscall # print the char
addu $t1,$t1,1 # go to next char
blt $t1,$t0,psLoop
donePrintStr:
# pop stack and return
addu $sp,$sp,8
jr $ra
########################################################
# printInt(n) - library method (class Lib)
# - prints integer in decimal format to standard output
# - parameters:
# - ($sp) - the integer to print
# - 4($sp) - (dummy) GC tag
# - 8($sp) - this-pointer
########################################################
printInt_Lib:
# pop value off stack, along with 'this'
lw $a0,($sp)
addu $sp,$sp,12
# print it
li $v0,1 # code for print-int
syscall
# return
jr $ra
########################################################
# printBool(n) - library method (class Lib)
# - prints boolean to standard output
# - parameters:
# - ($sp) - the boolean to print
# - 4($sp) - this-pointer
########################################################
printBool_Lib:
# pop value off stack, along with 'this'
lw $t0,($sp)
addu $sp,$sp,8
# print either 'true' or 'false', depending on the value
la $a0,falseString
beq $t0,$zero,skipPB
la $a0,trueString
skipPB:
li $v0,4 # code for print-string
syscall
# return
jr $ra
########################################################
# str.substring(n, k) - library method (class String)
# takes a substring of a string: Java: str.substring(n, k)
# - parameters:
# - ($sp) - k: one beyond index of last char in subrange
# - 4($sp) - (dummy) GC tag
# - 8($sp) - n: index of first char in subrange
# - 12($sp) - (dummy) GC tag
# - 16($sp) - str: string to take substring of
# - return value:
# - ($sp) - substring
########################################################
substring_String:
# save $ra by pushing onto stack
subu $sp,$sp,4
sw $ra,($sp)
# get string value off stack, test for null
lw $t0,20($sp)
beq $t0,$zero,nullPtrException
# get both indices and string length, and ensure that
# 0 <= n <= k <= length
lw $t0,-4($t0) # negative of string length
subu $t0,$zero,$t0 # string length
lw $t1,4($sp) # k
lw $t2,12($sp) # n
bgt $zero,$t2,strIndexOutOfBounds
bgt $t2,$t1,strIndexOutOfBounds
bgt $t1,$t0,strIndexOutOfBounds
# allocate memory
subu $s6,$t1,$t2 # # chars in target-string
addu $s6,$s6,7 # account for extra "class" (4) word + 3 to round up
srl $s6,$s6,2 # convert bytes-count to word-count
move $s7,$zero # (no object-bytes in string)
jal newObject
# store "String" tag in object-type field
la $t0,CLASS_String
sw $t0,-12($s7)
# store negative of count (=n-k) into object-length header-word
lw $t1,8($sp) # k
lw $t2,16($sp) # n
subu $t0,$t2,$t1 # value to store
sw $t0,-4($s7) # store value
# store result in return-spot on stack
lw $t3,24($sp) # source string pointer
sw $s7,24($sp) # store final result in return-spot on stack
# skip byte-copy loop if length is zero
beq $zero,$t0,doneSubCopyzz
# get pointers set up in preparation for copy
lw $t4,-8($t3) # # data words in source string
sll $t4,$t4,2 # # data bytes in source string
subu $t3,$t3,$t4 # addr. of first data word of source string (+8)
addu $t3,$t3,$t2 # addr. of first source data byte to be copied (+8)
subu $t1,$t3,$t0 # addr. beyond last source data byte to be copied (+8)
lw $t2,-8($s7) # # data words in target string
sll $t2,$t2,2 # # data bytes in target string
subu $t2,$s7,$t2 # addr. of first target data byte (+8)
############################################
# at this point:
# - we know that the string has a positive length
# - $t3 contains 8 + address of the first source-byte
# - $t1 contains 8 + limit-address of the first source-byte
# - $t2 contains 8 + address first target byte
############################################
# copy the bytes from source to target
subCopyLoopzz:
lb $t4,-8($t3)
sb $t4,-8($t2)
addu $t2,$t2,1
addu $t3,$t3,1
blt $t3,$t1,subCopyLoopzz
doneSubCopyzz:
# restore return address, store return value, pop stack
lw $ra,4($sp) # restore $ra
addu $sp,$sp,24 # pop stack
# return
jr $ra
########################################################
# length() - library method (class String)
# returns length of a string: Java: str.length()
# - parameters:
# - ($sp) - the string
# - return-value:
# - ($sp) - length of string
# - 4($sp) - (dummy) GC tag
########################################################
length_String:
# get string pointer
lw $t0,($sp)
# grow stack
subu $sp,$sp,4
# store GC tag
sw $s5,4($sp)
#lw $zero,4($sp)#**"" #--FOR MEMORY TAGGING
# push length onto stack
lw $t0,-4($t0) # -length
subu $t0,$zero,$t0
sw $t0,($sp) #store length
# return
jr $ra
########################################################
# str1.concat(str2) - library method (class String)
# (as in Java)
# - parameters:
# - ($sp) - the second string
# - 4($sp) - the first string
# - returns:
# - ($sp) - pointer to concatenated string
########################################################
concat_String:
# save $ra by pushing onto stack
subu $sp,$sp,4
sw $ra($sp)
# get string pointers and check parameter for null
lw $t0,4($sp)
beq $t0,$zero,nullPtrException
lw $t1,8($sp)
# get lengths of two strings; allocate object whose size
# is their sum divided by 4 (rounded up) plus 1
lw $t0,-4($t0) # negative size of second object
lw $t1,-4($t1) # negative size of first object
addu $s6,$t0,$t1 # sum of negative sizes
sra $s6,$s6,2 # negative word-size of char part
subu $s6,$zero,$s6 # word size of char part
addu $s6,$s6,1 # data word size, including v-table word
move $s7,$zero
jal newObject
# store "String" tag in object-type field
la $t0,CLASS_String
sw $t0,-12($s7)
# pop rtnVal, $ra and both parameters off stack; push rtnVal
# onto stack
lw $ra,4($sp) # return address
lw $t0,8($sp) # second object
lw $t1,12($sp) # first object
addu $sp,$sp,12 # pop
sw $s7,($sp) # store return value
# get negative sizes; sum and store in new object size-field
lw $t2,-4($t0) # negative length of second object
lw $t3,-4($t1) # negative length of first object
addu $t4,$t2,$t3 # sum of negative lengths
sw $t4,-4($s7) # store sum as negated target-string length
#########################################################
# at this point:
# - $t0 is pointer to second object
# - $t1 is pointer to first object
# - $t2 is negated length of second object
# - $t3 is negated length of first object
# - $s7 is pointer to new object
#########################################################
# compute addresses for moving data from first string
lw $t4,-8($t1) # # data words in first string
sll $t4,$t4,2 # # data bytes in first string
subu $t1,$t1,$t4 # addr. (+8) of first byte in first string
lw $t4,-8($s7) # # data words in new string
sll $t4,$t4,2 # # data bytes in new string
subu $s7,$s7,$t4 # addr. (+8) of first byte in new string
beq $zero,$t3,doneConcatLoop1zz # skip first loop is no bytes to copy
subu $t3,$t1,$t3 # limit (+8) address for first string
#########################################################
# at this point:
# - $t0 is pointer to second object
# - $t1 is address (+8) of first byte in first object
# - $t2 is negated length of second object
# - $t3 is limit-address (+8) of data in first object
# - $s7 is address (+8) of first byte in new object
# - note: if data-length of first object is zero, then
# we skip over this part, and go to 'doneConcatLoop1'
#########################################################
# copy the bytes from first source to target
concatLoop1zz:
lb $t4,-8($t1)
sb $t4,-8($s7)
addu $s7,$s7,1
addu $t1,$t1,1
blt $t1,$t3,concatLoop1zz
doneConcatLoop1zz:
# if second string is empty, skip rest of copy
beq $zero,$t2,doneConcatLoop2zz
# compute addresses for moving data from second string
lw $t4,-8($t0) # # data words in second string
sll $t4,$t4,2 # # data bytes in second string
subu $t1,$t0,$t4 # addr. (+8) of first byte in second string
subu $t3,$t1,$t2 # limit (+8) address for second string
#########################################################
# at this point:
# - $t1 is address (+8) of first byte in second object
# - $t3 is limit-address (+8) of data in second object
# - $s7 is address (+8) of next byte to write new object
# - note: if data-length of second object is zero, then
# we skip over this part, and go to 'doneConcatLoop2'
#########################################################
# copy the bytes from first source to target
concatLoop2zz:
lb $t4,-8($t1)
sb $t4,-8($s7)
addu $s7,$s7,1
addu $t1,$t1,1
blt $t1,$t3,concatLoop2zz
doneConcatLoop2zz:
concatRtnzz:
# return
jr $ra
########################################################
# str.charAt(n) - library method (class String)
# accesses a character in a string, as in Java
# - parameters:
# - ($sp) - the index, n
# - 4($sp) - dummy GC tag
# - 8($sp) - the string, str
# - returns:
# - ($sp) - the character found
# - 4($sp) - the dummy GC tag
########################################################
charAt_String:
# get string
lw $t0,8($sp)
# check that index is in bounds
lw $t1,-4($t0) # negative of # data words in string
subu $t3,$zero,$t1 # # chars in string
lw $t2,($sp) # index
bgeu $t2,$t3,strIndexOutOfBounds
# access element
lw $t1,-8($t0) # # data words in object
sll $t1,$t1,2 # - byte-offset from end of chars
subu $t1,$t2,$t1 # - address of first char in string, offset by 8
addu $t0,$t0,$t1 # - address of our char, offset by 8
lb $t0,-8($t0) # our char
# pop elements off stack, pushing rtnVal
addu $sp,$sp,4
sw $t0,($sp)
sw $s5,4($sp)
#lw $zero,4($sp)#**"" #--FOR MEMORY TAGGING
# return
jr $ra
########################################################
# intToString(n) - library method (class Lib)
# converts int to string: Java: ""+n
# - parameters:
# - ($sp) - the value to convert, n
# - 4($sp) - dummy GC tag
# - 8($sp) - this-pointer
# - returns:
# - ($sp) - the string, which is the string representation of
# the integer
########################################################
intToString_Lib:
# save return address on stack; allocate space for dummy GC tag
subu $sp,$sp,8
sw $ra,4($sp)
# save current sp
move $t0,$sp
# move constant 10 into $t3
li $t3,10
# get argument, negate if negative
lw $t1,8($sp)
bge $t1,$zero,itsNonNegLoop
subu $t1,$zero,$t1
# loop through, computing unsigned remainder by 10, and
# storing digits on stack until we reach 0
itsNonNegLoop:
divu $t1,$t3
mflo $t1 # quotient
mfhi $t4 # remainder
addu $t4,$t4,'0' # turn remainder into digit
subu $sp,$sp,4
sw $t4,($sp) # push digit onto stack
bne $t1,$zero,itsNonNegLoop
# push '-' if negative
lw $t4,8($t0)
bge $t4,$zero,itsSkipNeg
li $t4,'-'
subu $sp,$sp,4
sw $t4,($sp)
itsSkipNeg:
################################################
# At this point, all of our digits have been pushed
# onto the stack. $sp points to the first one;
# $t0 contains the limit-pointer (into which we need to
# write a GC tag).
################################################
# compute number of characters on stack (one word per character);
# write GC tag onto stack; push char-count onto stack
subu $s6,$t0,$sp
addu $t3,$s6,5 # GC tag (including for count-word, about to be pushed
sw $t3,($t0)
srl $s6,$s6,2
subu $sp,$sp,4
sw $s6,($sp)
# allocate memory
addu $s6,$s6,7 # 3 to round up, plus 4 for vtable word
srl $s6,$s6,2
move $s7,$zero # no "object" words in object
jal newObject
# restore char-count; pop it and return value from 'newObject'
lw $t0,4($sp)
addu $sp,$sp,8
# store "String" tag into class field
subu $s7,$s7,8 # address of header-1 word
la $t1,CLASS_String
sw $t1,-4($s7)
# store negative of char-count into header-2 word
subu $t0,$zero,$t0
sw $t0,4($s7)
lw $t1,($s7) # number of data words in string
sll $t1,$t1,2 # number data bytes in string
subu $t1,$s7,$t1 # first location to store chars in string
subu $t0,$t1,$t0 # limit address for chars in string
####################################################
# at this point:
# - $sp contains first source character address
# - $t1 contains first target character address
# - $t0 contains target-limit address
####################################################
# loop through and copy all elements as we pop them off the stack.
# (In this case, we know that there is it least one.)
itsLoop:
lw $t2,($sp)
addu $sp,$sp,4
sb $t2,($t1)
addu $t1,$t1,1
bne $t1,$t0,itsLoop
####################################################
# At this point
# - ($t0+15)&0xfffffffe is our return value
# - ($sp) contains garbage (old GC tag)
# - 4($sp) contains return address
####################################################
# adjust stack, restore return address; return
lw $ra,4($sp)
addu $sp,$sp,16
addu $t0,$t0,15
and $t0,$t0,0xfffffffc
sw $t0,($sp)
jr $ra
########################################################
# intToChar(n) - library method (class Lib)
# converts int to a one-character string: Java: ""+(char)(n&0xff)
# - parameters:
# - ($sp) - the value to convert, n
# - 4($sp) - dummy GC tag
# - 8($sp) - this-pointer
# - returns:
# - ($sp) - the string, which is the converted character
# - note: only the low 8 bits of the value n are used
########################################################
intToChar_Lib:
# save return address
subu $sp,$sp,4
sw $ra,($sp)
# allocate object
li $s6,2
move $s7,$zero
jal newObject
# restore $ra, get 'n', popping then and 'newObject' rtnVal
# off stack
lw $ra,4($sp)
lw $t1,8($sp)
addu $sp,$sp,16
# store "String" tag into class field
la $t0,CLASS_String
sw $t0,-12($s7)
# store data in string
sb $t1,-16($s7)
# store negative of size in header-word 2
li $t0,-1
sw $t0,-4($s7)
# store string pointer (return val) on stack for return
sw $s7,($sp)
# return
jr $ra
########################################################
# str1.compareTo(str2) - library method (class String)
# compares two strings as in Java
# - parameters:
# - ($sp) - second string
# - 4($sp) - first string
# - returns:
# - ($sp) - -1, 0, or 1 depending on whether str1 is
# lexographically less than, equal to or greater than str2
# - 4($sp) - (dummy) GC tag
########################################################
compareTo_String:
# get string pointers and check parameter for null
lw $t0,($sp) # second string
beq $t0,$zero,nullPtrException
lw $t1,4($sp) # first string
# get (negatives of) respective byte-lengths
lw $t2,-4($t0) # negative length of second string
lw $t3,-4($t1) # negative length of first string
# put tentative return value in $t5.
# The tentative return value is the one that we will use if we get
# to the end of the shorter string during our comparison-loop.
slt $t4,$t3,$t2
slt $t5,$t2,$t3
subu $t5,$t5,$t4
# at this point:
# - $t0 contains the pointer to the second string object
# - $t1 contains the pointer to the first string object
# - $t5 contains the value to return if the strings compare equal up
# to the length of the shortest word
# get begin-of-string addresses
lw $t2,-8($t0) # # data words in second string
lw $t3,-8($t1) # # data words in first string
sll $t2,$t2,2 # byte-offset to beginning of str2 (+8)
sll $t3,$t3,2 # byte-offset to beginning of str1 (+8)
subu $t0,$t0,$t2 # beginning of str1 address (+8)
subu $t1,$t1,$t3 # beginning of str2 address (+8)
# put $t1-limit into $t2
beq $zero,$t5,skipStrCmpLenzz
move $t2,$t3
skipStrCmpLenzz:
add $t2,$t1,$t2
# at this point:
# - $t0 contains 8 plus the address of the first data-byte of str2
# - $t1 contains 8 plus the address of the first data-byte of str1
# - $t2 contains 8 plus the address of the last data-type of str1
# - $t5 contains the value to return if the strings compare equal up
# to the length of the shortest word
#######################################################
# at this point, we have
# - $t5 containing the tentative return-value
# - $t1 containing address of first char in str2
# - $t2 containing limit for $t1
# - $t0 containing address of first char in str1
#######################################################
# loop through, until we find unequal words or we hit
# our limit
cmpLoopzz:
lw $t3,-8($t1) # word from str2
lw $t4,-8($t0) # word from str1
bne $t3,$t4,cmpNotEqualzz
addu $t1,$t1,4
addu $t0,$t0,4
bne $t1,$t2,cmpLoopzz
# # got to the end of one string: go set up return
j cmpHitLimitzz
cmpNotEqualzz:
# found unequal characters: return -1 or 1, depending on which is
# greater
slt $t5,$t4,$t3 # 1 if str2 > str1, else 0
sll $t5,$t5,1 # 2 if str2 > str1, else 0
subu $t5,$t5,1 # 1 if str2 > str1, else -1
cmpHitLimitzz:
sw $t5,($sp) # store value
sw $s5,4($sp) # GC tag
#lw $zero,4($sp)#**"" #--FOR MEMORY TAGGING
jr $ra # return
########################################################
# readLogicalChar (millicode)
# - logically reads a character from standard input
# - first checks character buffer, consuming it if possible
# - return-result:
# - returns character in $v0
# - side-effects:
# - reads a character
# - clobbers $t0
########################################################
readLogicalChar:
# check if we already have a character
lw $v0,lastCharRead
li $t0,-2
beq $t0,$v0 doReadCh
# we have our character from the buffer. Wipe out
# buffer and return
sw $t0,lastCharRead # store -2 into buffer (i.e. "empty")
jr $ra # return
doReadCh:
# we need to actually read a character: read and return
li $v0,12 # use system call to read a character
syscall
jr $ra # return
########################################################
# newObject (millicode)
# - allocates a new object on the heap
# - two-word header is set up properly
# - all non-header words in object are set to zero
# - parameters:
# - $s6 = first header-word, which is -1 if it is a data-array
# allocation, and is the number of data words in the object
# otherwise
# - $s7 - second header-word, which is the number of object
# words in the object (unless $s6 is -1, in which case it
# is the number of data words in the object
# - it is illegal for $s6 to be less than -1 (this is not checked)
# - it is illegal for $s7 to be less than 0 (this is checked)
# - return-result:
# - pushed onto the top of the stack
# - also returned in $s7
# - side-effects:
# - may trash all $tx registers and all $sx registers, except the
# "permanent" ones, which get updated with values that are
# consistent with the new space
########################################################
newObject:
# $s6 = # data words (or -1 if data-array allocation)
# - note: it is illegal for $s6 to be less than -1
# $s7 = # object words (# data words if data-array allocation)
# $ra = return address
## on return, pointer to new memory is on
## top of stack, and also in $s7
# abort if the object size is negative (this would be an array
# allocation)
blt $s7,$zero arraySizeOutOfBounds
# mark the fact that we have not yet GC'd for this allocation
move $t5,$zero
###### TEMPORARY #######
# for now, go a GC unconditionally, so that a full GC occurs
# every time we allocate an object
### let's not do that for now
# j doGC
gcJoin:
# Determine actual size of "before-header" portion.
# If negative (which would be -1), it really means 1
move $t3,$s6
bge $t3,$zero,newSkip
subu $t3,$zero,$t3 # 1
newSkip:
# at this point:
# $s6 contains the first header word
# $s7 contains the second header word, which is also the
# after-header word count
# $t3 contains the before-header word count
# $t5 is zero iff we have not GC'd for this allocation
# determine if we have enough memory available
addu $t0,$t3,$s7
sll $t0,$t0,2
addu $t0,$t0,8 # amount of memory needed
addu $t1,$t0,$s3
bgtu $t1,$s4,doGC
# at this point:
# $s3 points to beginning of segment, and
# $t1 points just past the end
# zero out the memory
move $t2,$s3
zeroObjLoop:
sw $zero,($s3)
#lw $zero,($s3)#**"" #--FOR MEMORY TAGGING
addu $s3,4
bltu $s3,$t1,zeroObjLoop
# at this point:
# $s3 has been updated to point to the next free slot,
# which is also the point just past our object
# compute pointer value and set up header-words
sll $t0,$s7,2 # number of post-header bytes
subu $t0,$s3,$t0 # pointer that we will return
# store header-values
sw $s6,-8($t0) # first header-word
#lw $zero,-8($t0)#**"H1" #--FOR MEMORY TAGGING
sw $s7,-4($t0) # second header-word
#lw $zero,-4($t0)#**"H2" #--FOR MEMORY TAGGING
# put return-value into $s7 and also push it onto top of stack
move $s7,$t0
subu $sp,$sp,4
sw $t0,($sp)
jr $ra
doGC:
#####################################################
# We need to do a garbage-collect
#####################################################
# print that we are doing a GC
# la $a0,gcMsg # prints message: "GC!"
# li $v0,4 # syscall-code for print-string
# syscall
# if we've already done a GC for this allocation, then
# we are actually out heap-memory: abort program
bne $t5,$zero,outOfHeapMemory
# save $s2 (our only rooted register) on the stack
# so that the garbage collector processes it
subu $sp,$sp,4
sw $s2,($sp)
# set $s3 to the address of the new segment and the
# end-limit of the new segment, respectively,
# Also, update cur_seg to refer to the other segment
lw $t0,cur_seg
move $t7,$s4
la $t6,seg1_start
la $s3,seg0_start
la $s4,seg0_end
sw $zero,cur_seg
bne $t0,$zero,skipGc1
la $t6,seg0_start
la $s3,seg1_start
la $s4,seg1_end
sw $s5,cur_seg
skipGc1:
li $t5,-2
lw $t0,stack_bottom
subu $t0,4
##################################
# TEMPORARY HACK TO EXERCISE GC
##################################
#lw $t1,heapFudge
#addu $t6,$t6,$t1
#addu $t1,$t1,4
#addu $s3,$s3,$t1 # fudge new heap pointer
###############################################################
# at this point:
# - $t6 contains the first address of the source space
# - $t7 contains the limit address of the source space
# - $s3 contains the first address of the target space
# - $s4 contains the limit address of the target space
# - cur_seg has been updated to refer to the target space
# - $t0 contains the address of the deepest stack element
# - $sp contains the address of the top stack element
# - $s2 is available for use, having been pushed onto the stack
# - $t5 contains the value -2
###############################################################
###### begin outer loop to copy all stack-direct objects ######
gcStackCopyLoop:
lw $t1,($t0) # current stack element
# test if we have a GC tag
sll $t2,$t1,31 # zero iff low bit was zero
bne $t2,$zero,gcBump # go skip data values if low bit not zero
# bump stack-address pointer
subu $t0,$t0,4
# if value is out of range (which includes null=0), and is
# therefore does not refer to an object on the heap, just go
# loop back and do the next one
bleu $t1,$t6,gcTestIterDone1
bgtu $t1,$t7,gcTestIterDone1
# if the object has already been moved, update the stack-value
# via the forwarding pointer
lw $t2,-8($t1) # possible forwarding tag
bne $t2,$t5,gcNoForward1 # if not forwarding tag, go copy
lw $t2,-4($t1) # forwarding pointer: object's new address
sw $t2,4($t0) # update stack value
j gcTestIterDone1 # do next iteration
gcNoForward1:
#########################################################
# we actually need to copy the object into the new space
#########################################################
# compute the amount of space that is needed
bge $t2,$zero,gcSkip2
subu $t2,$zero,$t2 # set to 1 if -1 (number of data words)
gcSkip2:
sll $t2,$t2,2
addu $t2,$t2,8
subu $t4,$t1,$t2 # address of first word of source
lw $t3,-4($t1) # number of object words (negative treated as zero)
bge $t3,$zero,gcH2Neg1
move $t3,$zero
gcH2Neg1:
sll $t3,$t3,2
addu $t3,$t3,$t1 # address one word past last word of source
addu $t2,$s3,$t2 # pointer to target object
#########################################################
# At this point:
# - $t0 contains the address of the stack slot we'll
# process next
# - $t1 contains the contents of the stack slot we're
# currently working on, which is a pointer to the source
# object (i.e., the address just beyond the object's header
# - $t2 contains the pointer to the target object
# - $t3 contains the limit address of the source object
# - $t4 contains the first address of the source object
# - $t5 contains the value -2
# - $t6 contains the first address of the source space
# - $t7 contains the limit address of the source space
# - $s3 contains the first unallocated address of the
# target space, which is also the first address of the
# target object
# - $s4 contains the limit address of the target space
# - $s5 contains the value 5
# - $s6-7 contain the original parameters to the call to
# 'newObject'
# - $sp contains the address of the top stack element
# - available for use: $s0-2
#########################################################
# swap first header word and first data word so that header
# can be found by "trailing finger" in the target space
lw $s0,($t4)
lw $s1,-8($t1)
sw $s1,($t4)
sw $s0,-8($t1)
# copy all source bytes to the target
gCinnerCopy1:
lw $s0,($t4)
sw $s0,($s3)
addu $t4,$t4,4
addu $s3,$s3,4
bltu $t4,$t3,gCinnerCopy1
###########################################################
# All bytes have been copied to the target space. We still
# need to:
# - set up forwarding pointer in source object
# - update the pointer in the current stack slot
###########################################################
# set up the forwarding pointer
sw $t5,-8($t1) # -2 in first header-slot
sw $t2,-4($t1) # forwarding pointer in second header-slot
# update the stack slot with the address in the target space
sw $t2,4($t0)
#lw $zero,-8($t2)#**"H1" #--FOR MEMORY TAGGING
#lw $zero,-4($t2)#**"H2" #--FOR MEMORY TAGGING
# go handle next stack slot (testing if done)
j gcTestIterDone1
gcBump:
#### we have a GC tag. Bytes to skip: tag value + 3.
subu $t0,$t0,$t1
subu $t0,$t0,3
gcTestIterDone1:
bgeu $t0,$sp,gcStackCopyLoop
###### end outer loop to copy all stack-direct objects ######
#############################################################
# We have finished processing the stack elements. Now we need
# to update elements in the heap itself. This may itself involve
# moving additional objects
#############################################################
#########################################################
# At this point:
# - $t5 contains the value -2
# - $t6 contains the first address of the source space
# - $t7 contains the limit address of the source space
# - $s3 contains the first unallocated address of the
# target space
# - $s4 contains the limit address of the target space
# - $s5 contains the value 5
# - $s6-7 contain the original parameters to the call to
# 'newObject'
# We want to set things up so that in addition:
# - $t0 is the "trailing finger", containing the address
# of the first slot in target space that we have yet
# to process.
# Then during processing:
# - $t1 will contain the contents of the heap slot we're
# currently working on, which is a pointer to the source
# object
# And when we're actually copying an object:
# - $t2 will contain pointer to the target object
# - $t3 will contain the limit address of the source object
# - $t4 will contain the first address of the source object
# - $s1 will contain the the limit address for the current
# object that tells where the pointers in the object end
# - available for use: $s0
##########################################################
# set $t0 to be at the beginning of target-space
lw $t1,cur_seg
la $t0,seg0_start
beq $t1,$zero,gcSkip4
la $t0,seg1_start
##################################
# TEMPORARY HACK TO EXERCISE GC
##################################
#lw $s0,heapFudge
#addu $s0,$s0,4
#addu $t0,$t0,$s0
#sw $s0,heapFudge
gcSkip4:
# if there were no objects put into the heap during stack
# processing, we're done, so go finish up
bgeu $t0,$s3,gcFinishUp
###### begin outer loop to copy all non-stack-direct objects ######
gcHeapCopyLoop:
# check if we have a data array
lw $t1,($t0) # first header word for current object
bge $t1,$zero,gcNotDataArray # test for neg. num (actually -1)
# We have a -1 header-word, which means this object has no pointers.
# we need to swap the -1 with the vtable pointer in the object,
# and then skip over it then loop back to do next object.
skipToNextObj:
lw $s0,4($t0) # un-swap vtable pointer ...
sw $s0,($t0) # ...
sw $t1,4($t0) # ... and -1 header-word
lw $t1,8($t0) # data words in (object position of) array
addu $t1,$t1,3 # add in # header words
sll $t1,$t1,2 # convert to byte-count
addu $t0,$t0,$t1 # skip over object
j gcTestIterDone2 # go do next object, if any
gcNotDataArray:
# get data count for object; swap header-word with first word
# of object so that they're back in the right place
sll $t2,$t1,2 # # data bytes
addu $t2,$t2,8 # to skip header words
addu $t2,$t0,$t2 # pointer to new object
lw $t3,-8($t2) # word to swap
sw $t1,-8($t2) # store header word
sw $t3,($t0) # restore first word of object
###################################################
# at this point:
# - the object has been restored to normal status
# - $t0 contains the address of the first word in the object
# (pretty useless at this point)
# - $t1 contains the first header word (# data objects)
# - $t2 contains a pointer to the object
###################################################
########### new stuff
# If there is a -12 header word, skip to next object if it is
# CLASS__DataArray
# beq $t1,$zero,noH3 # skip if vtable pointer
# lw $t3,-12($t2) # get vtable pointer
# subu $t3,CLASS__DataArray
# subu $t0,$t2,8 # set up $t0 in anticipation of skip
# beq $zero,$t3,skipToNextObj # skip if it's a data array
noH3:
lw $t3,-4($t2) # # object words (negative treated as zero)
bge $t3,$zero,gcH2Neg2
move $t3,$zero
gcH2Neg2:
sll $t3,$t3,2 # # object bytes
move $t0,$t2 # address of first pointer in object
add $s1,$t2,$t3 # limit address for this object
#####################################################
# At this point, we have to "translate" all pointers,
# starting at $t0 to (but not including) $s1
#####################################################
# if there are no pointer-slots (i.e., $t0=$s1), skip this
# part
beq $t0,$s1,gcTestIterDone2
gcNextPointerInObject:
# get pointer from object
lw $t1,($t0)
# if value is out of range, and is therefore does not refer
# to an object, just go loop back and do the next one
bleu $t1,$t6,gcGoNextPointerSlot
bgtu $t1,$t7,gcGoNextPointerSlot
# if the object has already been moved, update the stack-value
# via the forwarding pointer
lw $t8,-8($t1) # possible forwarding tag
bne $t8,$t5,gcNoForward2 # if not forwarding tag, go copy
lw $t8,-4($t1) # forwarding pointer: object's new address
sw $t8,($t0) # update pointer in object
j gcGoNextPointerSlot # do next iteration
gcNoForward2:
#########################################################
# we actually need to copy the object into the new space
#########################################################
#########################################################
# At this point:
# - $t0 contains the address of the heap-slot we're translating
# - $t1 will contain the contents of the heap-slot we're
# currently working on, which is a pointer to the source
# object
# - $t2 will contains pointer to the object we're in the
# middle of translating
# - $t5 contains the value -2
# - $t6 contains the first address of the source space
# - $t7 contains the limit address of the source space
# - $s3 contains the first unallocated address of the
# target space, which will also be the first address
# of the target object
# - $s4 contains the limit address of the target space
# - $s5 contains the value 5
# - $s6-7 contain the original parameters to the call to
# 'newObject'
# Then during processing:
# And when we're actually copying an object:
# - $t3 will contain the limit address of the source object
# - $t4 will contain the first address of the source object
# - $s1 will contain the the limit address for the current
# object that tells where the pointers in the object end
# - $t8 will contain a pointer to the target object
# - available for use: $s0, $t8, $t9
##########################################################
# compute the amount of space that is needed
bge $t8,$zero,gcSkip5
li $t8,1 # set to 1 if -1
gcSkip5:
sll $t8,$t8,2
addu $t8,$t8,8
subu $t4,$t1,$t8 # address of first word of source
lw $t3,-4($t1)
bge $t3,$zero,gcNoNeg
move $t3,$zero
gcNoNeg:
sll $t3,$t3,2
addu $t3,$t3,$t1 # address one word past last word of source
addu $t8,$s3,$t8 # pointer to target object
#########################################################
# At this point:
# - $t0 contains the address of the stack slot we'll
# process next
# - $t1 contains the contents of the stack slot we're
# currently working on, which is a pointer to the source
# object
# - $t2 will contains pointer to the object we're in the
# middle of translating
# - $t3 contains the limit address of the source object
# - $t4 contains the first address of the source object
# - $t5 contains the value -2
# - $t6 contains the first address of the source space
# - $t7 contains the limit address of the source space
# - $t8 contains the pointer to the target object
# - $s1 contains the the limit address for the current
# object that tells where the pointers in the object end
# - $s3 contains the first unallocated address of the
# target space, which is also the first address of the
# target object
# - $s4 contains the limit address of the target space
# - $s5 contains the value 5
# - $s6-7 contain the original parameters to the call to
# 'newObject'
# - $sp contains the address of the top stack element
# - available for use: $s0, $t9
#########################################################
# swap first header word and first data word so that header
# can be found by "trailing finger"
lw $s0,($t4)
lw $t9,-8($t1)
sw $t9,($t4)
sw $s0,-8($t1)
# copy all source bytes to the target
gCinnerCopy2:
lw $s0,($t4)
sw $s0,($s3)
addu $t4,$t4,4
addu $s3,$s3,4
bltu $t4,$t3,gCinnerCopy2
###########################################################
# All bytes have been copied to the target space. We still
# need to:
# - set up forwarding pointer in source object
# - update the pointer in the current stack slot
###########################################################
# set up the forwarding pointer
sw $t5,-8($t1) # -2 in first header-slot
sw $t8,-4($t1) # forwarding pointer in second header-slot
# update the heap-slot with the address in the target space
sw $t8,($t0)
gcGoNextPointerSlot:
# bump $t0 to next slot in object; if not done, loop back
addu $t0,$t0,4
bltu $t0,$s1,gcNextPointerInObject
gcTestIterDone2:
bltu $t0,$s3,gcHeapCopyLoop
###### end outer loop to copy all non-stack-direct objects ######
gcFinishUp:
# restore $s2 to its updated value by popping off stack
lw $s2,($sp)
addu $sp,$sp,4
# mark us as having already GC'd
move $t5,$s5
# go try and allocate again
j gcJoin
########################################################
# vm_init (millicode)
# - initialzes the virtual machine
# - values 5 stored in $s5
# - zero ("this pointer") stored in $s2
# - heap and heap-limit pointers stored respectively in $s3 and $s4
# - address of bottom of stack stored in 'stack_bottom' memory
# location
# - (note: 'cur_seg' memory location is already set to 0)
########################################################
vm_init:
# mark bottom of stack
sw $sp,stack_bottom
#move $sp,$sp#**"stack pointer" #--FOR MEMORY TAGGING
# set "this" pointer to be null, for now
move $s2,$zero
#move $s2,$s2#**"this pointer" #--FOR MEMORY TAGGING
#set up the "five" register
li $s5,5
#move $s5,$s5#**"constant 5" #--FOR MEMORY TAGGING
la $s3,seg0_start
#move $s3,$s3#**"next-avail-heap" #--FOR MEMORY TAGGING
la $s4,seg0_end
#move $s4,$s4#**"end-heap" #--FOR MEMORY TAGGING
# return
jr $ra
########################################################
# divide (millicode)
# - divides first arg by second (signed divide)
# - aborts if divisor is zero
# - follows calling conventions for library methods
# - parameters:
# - ($sp) divisor
# - 4($sp) (dummy) GC tag
# - 8($sp) dividend
# - 12($sp) (dummy) GC tag
# - return value:
# - ($sp) result
# - 4($sp) (dummy) GC tag
########################################################
divide:
# get parameters; abort if divisor zero
lw $t0,($sp)
lw $t1,8($sp)
beq $t0,$zero,divByZeroError
# perform division
div $t1,$t0
mflo $t0
# store result, adjust stack and return
addu $sp,$sp,8 # adjust stack
sw $t0,($sp) # store result
jr $ra
########################################################
# remainder (millicode)
# - takes remainder first arg divided by second (signed divide)
# - aborts if divisor is zero
# - follows calling conventions for library methods
# - parameters:
# - ($sp) divisor
# - 4($sp) (dummy) GC tag
# - 8($sp) dividend
# - 12($sp) (dummy) GC tag
# - return value:
# - ($sp) result
# - 4($sp) (dummy) GC tag
########################################################
remainder:
# get parameters; abort if divisor zero
lw $t0,($sp)
lw $t1,8($sp)
beq $t0,$zero,divByZeroError
# perform division
div $t1,$t0
mfhi $t0
# store result, adjust stack and return
addu $sp,$sp,8 # adjust stack
sw $t0,($sp) # store result
jr $ra
########################################################
# checkCast (millicode) - checks that a cast is legal
# - aborts if null
# - aborts if cast is illegal cast
# - parameters:
# - ($sp) object to check
# - $t0 address of vtable for target-class
# - $t1 address one past vtable address of last
# subclass of target-class
# - return value:
# - ($sp) object to check (now checked)
# - side-effects: clobbers $t2 and $t3
########################################################
checkCast:
# get object, allow immediately if null
lw $t2,($sp)
beq $t2,$zero,checkCastReturn
# get vtable address of object, abort if less than
# lower limit or greater then or equal to higher
# limit
lw $t2,-12($t2) # vtable address
bge $t2,$t1,castException
blt $t2,$t0,castException
# return, leaving object unchanged on stack
checkCastReturn:
jr $ra
# checkCast:
# # get object, allow immediately if null
# lw $t2,($sp)
# beq $t2,$zero,checkCastReturn
#
# # get vtable address of object (using Object vtable
# # address for arrays)
# lw $t3,-8($t2) # <= 0 if array
# lw $t2,-12($t2) # vtable address (unless array)
# bgt $t3,$zero,skipArrayCast
# la $t2,CLASS_Object
#
# # get vtable address of object, abort if less than
# # lower limit or greater then or equal to higher
# # limit
# skipArrayCast:
# bge $t2,$t1,castException
# blt $t2,$t0,castException
#
# # return, leaving object unchanged on stack
# checkCastReturn:
# jr $ra
########################################################
# instanceOf (millicode) - tests whether an object is
# a member of a given class (or subclass)
# - returns false if object is null
# - parameters:
# - ($sp) object to check
# - $t0 address of vtable for target-class
# - $t1 address one past vtable address of last
# subclass of target-class
# - return value:
# - ($sp) true (1) or false (0), depending on whether
# object is a member
# - side-effects: clobbers $t2 and $t3
########################################################
instanceOf:
# get object, go return false if null
lw $t2,($sp)
beq $t2,$zero,doneInstanceOf
# get vtable address of object, determine if we're >= the
# lower limit, and if we're < the higher limit
lw $t2,-12($t2) # vtable address
sge $t0,$t2,$t0 # are we >= the lower limit?
slt $t1,$t2,$t1 # are we < the higher limit?
# store the AND of the two conditions onto the stack; return
and $t2,$t0,$t1
sw $t2,($sp)
doneInstanceOf: # if we reach here via branch, stack-top is zero,
# which will now represent false
jr $ra
# instanceOf:
# # get object, go return false if null
# lw $t2,($sp)
# beq $t2,$zero,doneInstanceOf
#
# # get vtable address of object. If it's an array
# # (which would be H1 <= 0), use vtable address for Object
# lw $t3,-8($t2) # <= 0 if array
# lw $t2,-12($t2) # vtable address (unless array)
# bgt $t3,$zero,skipArrayInstanceOf
# la $t2,CLASS_Object
#
# # get vtable address of object, abort if less than
# # lower limit or greater then or equal to higher
# # limit
# skipArrayInstanceOf:
# sge $t0,$t2,$t0
# slt $t1,$t2,$t1
#
# # store the AND of the two conditions onto the stack; return
# and $t2,$t0,$t1
# doneInstanceOf: # if we reach here via branch, we know $t2=0
# sw $t2,($sp)
# jr $ra
###########################################################
# jump-targets to terminate program:
# - exit: returns normally
# - outOfHeapMemory: prints "out of memory" error and returns
###########################################################
exitError:
# assumes $a0 has pointer to null-terminated string
# print the string
li $v0,4 # syscall-code for print-string
syscall
exit:
# print termination message
li $v0,4
la $a0,exitString
syscall
# terminate execution
li $v0,10 #syscall-code for "exit"
syscall
outOfHeapMemory:
la $a0,heapMemoryMsg
j exitError
divByZeroError:
la $a0,divByZeroMsg
j exitError
strIndexOutOfBounds:
la $a0,strIndexOutOfBoundsMsg
j exitError
arrayIndexOutOfBounds:
la $a0,arrayIndexOutOfBoundsMsg
j exitError
arraySizeOutOfBounds:
la $a0,arraySizeOutOfBoundsMsg
j exitError
nullPtrException:
la $a0,nullPtrExceptionMsg
j exitError
badIntegerFormat:
la $a0,badIntegerFormatMsg
j exitError
castException:
la $a0,castExceptionMsg
j exitError
############## data section ################
.data
.align 2
cur_seg:
.word 0
lastCharRead:
.word -2 # -2 => no buffered character
heapMemoryMsg:
.asciiz "ERROR: out of heap memory\n"
divByZeroMsg:
.asciiz "ERROR: divide by zero\n"
strIndexOutOfBoundsMsg:
.asciiz "ERROR: string index out of bounds\n"
arrayIndexOutOfBoundsMsg:
.asciiz "ERROR: array index out of bounds\n"
arraySizeOutOfBoundsMsg:
.asciiz "ERROR: array size out of bounds\n"
nullPtrExceptionMsg:
.asciiz "ERROR: null-pointer exception\n"
badIntegerFormatMsg:
.asciiz "ERROR: attempt to read badly formatted integer\n"
castExceptionMsg:
.asciiz "ERROR: illegal cast\n"
gcMsg:
.asciiz "\nGC!\n"
nullStr:
.asciiz "null"
trueString:
.asciiz "true"
falseString:
.asciiz "false"
exitString:
.asciiz "Program terminated.\n"
.align 2
stack_bottom:
.word 0
#heapFudge: # temporary fudge amount to exercise GC
# .word 0
seg0_start:
.space 0x100000
seg0_end:
seg1_start:
.space 0x100000
seg1_end:
|
MODULE __printf_handle_B
SECTION code_clib
PUBLIC __printf_handle_B
EXTERN __printf_number
EXTERN __printf_set_base
EXTERN __printf_disable_plus_flag
__printf_handle_B:
IF __CPU_INTEL__ | __CPU_GBZ80__
ld c,2
call __printf_set_base
call __printf_disable_plus_flag
ELSE
ld (ix-9),2
res 1,(ix-4) ;disable '+' flag
ENDIF
ld c,0 ;unsigned
jp __printf_number
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; wAx
; Integrated Monitor Tools
; (c)2020, Jason Justian
;
; Release 1 - May 16, 2020
; Release 2 - May 23, 2020
; Release 3 - May 30, 2020
; Assembled with XA
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Copyright (c) 2020, Jason Justian
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; LABEL DEFINITIONS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
* = $6000
; Configuration
LIST_NUM = $10 ; Display this many lines
TOOL_COUNT = $09 ; How many tools are there?
T_DIS = "." ; Wedge character . for disassembly
T_ASM = "@" ; Wedge character @ for assembly
T_MEM = ":" ; Wedge character : for memory dump
T_TST = $b2 ; Wedge character = for tester
T_BRK = "!" ; Wedge character ! for breakpoint
T_REG = ";" ; Wedge character ; for register set
T_EXE = $5f ; Wedge character left-arrow for code execute
T_SAV = $b1 ; Wedge character > for save
T_LOA = $b3 ; Wedge character < for load
FWDR = "*" ; Forward Relative Branch Character
DEVICE = $08 ; Save device
; System resources - Routines
GONE = $c7e4
CHRGET = $0073
CHRGOT = $0079
PRTFIX = $ddcd ; Print base-10 number
SYS = $e133 ; BASIC SYS start
SYS_BRK = $e133 ; BASIC SYS continue after BRK
SYS_TAIL = $e144 ; BAIC SYS end
CHROUT = $ffd2
WARM_START = $0302 ; BASIC warm start vector
READY = $c002 ; BASIC warm start with READY.
NX_BASIC = $c7ae ; Get next BASIC command
CUST_ERR = $c447 ; Custom BASIC error message
SYNTAX_ERR = $cf08 ; BASIC syntax error
ERROR_NO = $c43b ; Show error in Accumulator
SETLFS = $ffba ; Setup logical file
SETNAM = $ffbd ; Setup file name
SAVE = $ffd8 ; Save
LOAD = $ffd5 ; Load
CLOSE = $ffc3 ; Close logical file
; System resources - Vectors and Pointers
IGONE = $0308 ; Vector to GONE
CBINV = $0316 ; BRK vector
BUFPTR = $7a ; Pointer to buffer
ERROR_PTR = $22 ; BASIC error text pointer
SYS_DEST = $14 ; Pointer for SYS destination
; System resources - Data
KEYWORDS = $c09e ; Start of BASIC kewords for detokenize
BUF = $0200 ; Input buffer
CHARAC = $07 ; Temporary character
KEYBUFF = $0277 ; Keyboard buffer and size, for automatically
CURLIN = $39 ; Current line number
KBSIZE = $c6 ; advancing the assembly address
MISMATCH = $c2cd ; "MISMATCH"
KEYCVTRS = $028d ; Keyboard codes
LSTX = $c5 ; Keyboard matrix
; System resources - Registers
ACC = $030c ; Saved Accumulator
XREG = $030d ; Saved X Register
YREG = $030e ; Saved Y Register
PROC = $030f ; Saved Processor Status
; Constants
; Addressing mode encodings
INDIRECT = $10 ; e.g., JMP ($0306)
INDIRECT_X = $20 ; e.g., STA ($1E,X)
INDIRECT_Y = $30 ; e.g., CMP ($55),Y
ABSOLUTE = $40 ; e.g., JSR $FFD2
ABSOLUTE_X = $50 ; e.g., STA $1E00,X
ABSOLUTE_Y = $60 ; e.g., LDA $8000,Y
ZEROPAGE = $70 ; e.g., BIT $A2
ZEROPAGE_X = $80 ; e.g., CMP $00,X
ZEROPAGE_Y = $90 ; e.g., LDX $FA,Y
IMMEDIATE = $a0 ; e.g., LDA #$2D
IMPLIED = $b0 ; e.g., INY
RELATIVE = $c0 ; e.g., BCC $181E
; Other constants
TABLE_END = $f2 ; Indicates the end of mnemonic table
QUOTE = $22 ; Quote character
LF = $0d ; Linefeed
CRSRUP = $91 ; Cursor up
CRSRRT = $1d ; Cursor right
RVS_ON = $12 ; Reverse on
RVS_OFF = $92 ; Reverse off
; wAx workspace
WORK = $a4 ; Temporary workspace (2 bytes)
MNEM = $a4 ; Current Mnemonic (2 bytes)
EFADDR = $a6 ; Program Counter (2 bytes)
CHARDISP = $a8 ; Character display for Memory (2 bytes)
LANG_PTR = $a8 ; Language Pointer (2 bytes)
OPCODE = $aa ; Assembly target for hypotesting
OPERAND = $ab ; Operand storage (2 bytes)
IDX_OUT = $ad ; Buffer index - Output
IDX_IN = $ae ; Buffer index - Input
TOOL_CHR = $af ; Current function (T_ASM, T_DIS)
RB_FORWARD = $10 ; Relative Branch Forward
OUTBUFFER = $0218 ; Output buffer (24 bytes)
INBUFFER = $0230 ; Input buffer (22 bytes)
IDX_SYM = $024e ; Temporary symbol index storage
INSTSIZE = $0250 ; Instruction size
RB_OPERAND = $0251 ; RB Operand
TEMP_CALC = $0252 ; Temporary calculation
INSTDATA = $0254 ; Instruction data (2 bytes)
BREAKPOINT = $0256 ; Breakpoint data (3 bytes)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; INSTALLER
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Install: jsr SetupVec ; Set up vectors (IGONE and BRK)
lda #<Intro ; Announce that wAx is on
ldy #>Intro ; ,,
jsr PrintStr ; ,,
jmp (READY) ; READY.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MAIN PROGRAM
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
main: jsr CHRGET ; Get the character from input or BASIC
ldy #$00 ; Is it one of the wedge characters?
-loop: cmp ToolTable,y ; ,,
beq Prepare ; If so, run the selected tool
iny ; Else, check the characters in turn
cpy #TOOL_COUNT ; ,,
bne loop ; ,,
jsr CHRGOT ; Restore flags for the found character
jmp GONE+3 ; +3 because the CHRGET is already done
; Prepare for Tool Run
; A wedge character has been entered, and will now be interpreted as a wedge
; command. Prepare for execution by
; (1) Setting a return point
; (2) Putting the tool's start address-1 on the stack
; (3) Transcribing from BASIC or input buffer to the wAx input buffer
; (4) Reading the first four hexadecimal characters used by all wAx tools and
; setting the Carry flag if there's a valid 16-bit number provided
; (5) RTS to route to the selected tool
Prepare: sta TOOL_CHR ; Save A in X so Prepare can set TOOL_CHR
lda #>Return-1 ; Push the address-1 of Return onto the stack
pha ; as the destination for RTS of the
lda #<Return-1 ; selected tool
pha ; ,,
lda ToolAddr_H,y ; Push the looked-up address-1 of the selected
pha ; tool onto the stack. The RTS below will
lda ToolAddr_L,y ; pull off the address and route execution
pha ; to the appropriate tool
jsr ResetIn ; Initialize the input index for write
jsr Transcribe ; Transcribe from CHRGET to INBUFFER
lda #$ef ; $0082 BEQ $008a -> BEQ $0073 (maybe)
sta $83 ; ,,
RefreshPC: jsr ResetIn ; Re-initialize for buffer read
jsr Buff2Byte ; Convert 2 characters to a byte
bcc main_r ; Fail if the byte couldn't be parsed
sta EFADDR+1 ; Save to the EFADDR high byte
jsr Buff2Byte ; Convert next 2 characters to byte
bcc main_r ; Fail if the byte couldn't be parsed
sta EFADDR ; Save to the EFADDR low byte
main_r: rts ; Pull address-1 off stack and go there
; Return from Wedge
; Return in one of two ways:
; (1) In direct mode, to a BASIC warm start without READY.
; (2) In a program, find the next BASIC command
Return: jsr DirectMode ; If in Direct Mode, warm start without READY.
bne in_program ; ,,
jmp (WARM_START) ; ,,
in_program: jmp NX_BASIC ; Otherwise, continue to next BASIC command
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; COMMON LIST COMPONENT
; Shared entry point for Disassembler and Memory Dump
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
List: bcc list_r ; Bail if the address is no good
jsr DirectMode ; If the tool is in direct mode,
bne start_list ; cursor up to overwrite the original input
lda #CRSRUP ; ,,
jsr CHROUT ; ,,
start_list: ldx #LIST_NUM ; Default if no number has been provided
ListLine: txa
pha
lda #$00
sta IDX_OUT
jsr BreakInd ; Indicate breakpoint, if it's here
lda TOOL_CHR ; Start each line with the wedge character, so
jsr CharOut ; the user can chain commands
lda EFADDR+1 ; Show the address
jsr Hex ; ,,
lda EFADDR ; ,,
jsr Hex ; ,,
lda TOOL_CHR ; What tool is being used?
cmp #T_MEM ; Default to disassembler
beq to_mem ; ,,
jsr Space ; Space goes after address for Disassembly
jsr Disasm
jmp continue
to_mem: lda #T_MEM ; The .byte entry character goes after the
jsr CharOut ; address for memory display
jsr Memory ; ,,
continue: jsr PrintBuff
pla
tax
ldy LSTX ; Exit if STOP key is pressed
cpy #$18 ; ,,
beq list_r ; ,,
dex ; Exit if loop is done
bne ListLine ; ,,
inx ; But if the loop is done, but a SHift key
lda KEYCVTRS ; is engaged, then go back for one more
and #$01 ; ,,
bne ListLine ; ,,
list_r: jmp EnableBP ; Re-enable breakpoint, if necessary
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; DISASSEMBLER COMPONENTS
; https://github.com/Chysn/wAx/wiki/1-6502-Disassembler
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Disassemble
; Disassemble a single instruction at the program counter
Disasm: ldy #$00 ; Get the opcode
lda (EFADDR),y ; ,,
jsr Lookup ; Look it up
bcc Unknown ; Clear carry indicates an unknown opcode
jsr DMnemonic ; Display mnemonic
jsr Space
lda INSTDATA+1 ; Pass addressing mode to operand routine
jsr DOperand ; Display operand
jmp NextValue ; Advance to the next line of code
; Unknown Opcode
Unknown: lda #T_MEM ; Byte entry before an unknown byte
jsr CharOut ; ,,
lda INSTDATA ; The unknown opcode is still here
jsr Hex
jmp NextValue
; Mnemonic Display
DMnemonic: lda MNEM+1 ; These locations are going to rotated, so
pha ; save them on a stack for after the
lda MNEM ; display
pha ; ,,
ldx #$03 ; Three characters...
-loop: lda #$00
sta CHARAC
ldy #$05 ; Each character encoded in five bits, shifted
shift_l: lda #$00 ; as a 24-bit register into CHARAC, which
asl MNEM+1 ; winds up as a ROT0 code (A=1 ... Z=26)
rol MNEM ; ,,
rol CHARAC ; ,,
dey
bne shift_l
lda CHARAC
;clc ; Carry is clear from the last ROL
adc #"@" ; Get the PETSCII character
jsr CharOut
dex
bne loop
pla
sta MNEM
pla
sta MNEM+1
mnemonic_r: rts
; Operand Display
; Dispatch display routines based on addressing mode
DOperand: cmp #IMPLIED ; Handle each addressing mode with a subroutine
beq mnemonic_r ; Implied has no operand, so it goes to some RTS
cmp #RELATIVE
beq DisRel
cmp #IMMEDIATE
beq DisImm
cmp #ZEROPAGE ; Subsumes all zeropage modes
bcs DisZP
cmp #ABSOLUTE ; Subsumes all absolute modes
bcs DisAbs
; Fall through to DisInd, because it's the only one left
; Disassemble Indirect Operand
DisInd: pha
lda #"("
jsr CharOut
pla
cmp #INDIRECT
bne ind_xy
jsr Param_16
jmp CloseParen
ind_xy: pha
jsr Param_8
pla
cmp #INDIRECT_X
bne ind_y
jsr Comma
lda #"X"
jsr CharOut
jmp CloseParen
ind_y: jsr CloseParen
jsr Comma
lda #"Y"
jmp CharOut
; Disassemble Immediate Operand
DisImm: lda #"#"
jsr CharOut
jmp Param_8
; Disassemble Zeropage Operand
DisZP: pha
jsr Param_8
pla
sec
sbc #ZEROPAGE
jmp draw_xy ; From this point, it's the same as Absolute
; Disassemble Relative Operand
DisRel: jsr HexPrefix
jsr NextValue ; Get the operand of the instruction, advance
; the program counter. It might seem weird to
; advance the PC when I'm operating on it a
; few lines down, but I need to add two
; bytes to get the offset to the right spot.
; One of those bytes is here, and the other
; comes from setting the Carry flag before
; the addition below
sta WORK
and #$80 ; Get the sign of the operand
beq sign
ora #$ff ; Extend the sign out to 16 bits, if negative
sign: sta WORK+1 ; Set the high byte to either $00 or $ff
lda WORK
sec ; sec here before adc is not a mistake; I need
adc EFADDR ; to account for the instruction address
sta WORK ; (see above)
lda WORK+1 ;
adc EFADDR+1 ;
jsr Hex ; No need to save the high byte, just show it
lda WORK ; Show the low byte of the computed address
jmp Hex ; ,,
; Disassemble Absolute Operand
DisAbs: pha ; Save addressing mode for use later
jsr Param_16
pla
sec
sbc #ABSOLUTE
draw_xy: ldx #"X"
cmp #$10
beq abs_ind
ldx #"Y"
cmp #$20
beq abs_ind
rts
abs_ind: jsr Comma ; This is an indexed addressing mode, so
txa ; write a comma and index register
jmp CharOut ; ,,
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MEMORY EDITOR COMPONENTS
; https://github.com/Chysn/wAx/wiki/4-Memory-Editor
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MemEditor: ldy #$00 ; This is Assemble's entry point for .byte
-loop: jsr Buff2Byte
bcc edit_exit ; Bail out on the first non-hex byte
sta (EFADDR),y
iny
cpy #$04
bne loop
edit_exit: cpy #$00
beq edit_r
tya
tax
jsr Prompt ; Prompt for the next address
jsr ClearBP ; Clear breakpoint if anything was changed
edit_r: rts
; Text Editor
; If the input starts with a quote, add characters until we reach another
; quote, or 0
TextEdit: ldy #$00 ; Y=Data Index
-loop: jsr CharGet
beq edit_exit ; Return to MemEditor if 0
cmp #QUOTE ; Is this the closing quote?
beq edit_exit ; Return to MemEditor if quote
sta (EFADDR),y ; Populate data
iny
cpy #$10 ; String size limit
beq edit_exit
jmp loop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ASSEMBLER COMPONENTS
; https://github.com/Chysn/wAx/wiki/2-6502-Assembler
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Assemble: bcc asm_r ; Bail if the address is no good
lda INBUFFER+4 ; If the user just pressed Return at the prompt,
beq asm_r ; go back to BASIC
-loop: jsr CharGet ; Look through the buffer for either
beq test ; 0, which should indicate implied mode, or:
cmp #FWDR ; * = Handle forward relative branching
beq HandleFwd ; ,,
cmp #T_MEM ; . = Start .byte entry (route to hex editor)
beq MemEditor ; ,,
cmp #QUOTE ; " = Start text entry (route to text editor)
beq TextEdit ; ,,
cmp #"$" ; $ = Parse the operand
bne loop ; ,,
jsr GetOperand ; Once $ is found, then grab the operand
test: jsr Hypotest ; Line is done; hypothesis test for a match
bcc AsmError ; Clear carry means the test failed
ldy #$00 ; A match was found! Transcribe the good code
lda OPCODE ; to the program counter. The number of bytes
sta (EFADDR),y ; to transcribe is stored in the INSTSIZE memory
ldx INSTSIZE ; location.
cpx #$02 ; Store the low operand byte, if indicated
bcc nextline ; ,,
lda OPERAND ; ,,
iny ; ,,
sta (EFADDR),y ; ,,
cpx #$03 ; Store the high operand byte, if indicated
bcc nextline ; ,,
lda OPERAND+1 ; ,,
iny ; ,,
sta (EFADDR),y ; ,,
nextline: jsr ClearBP ; Clear breakpoint on successful assembly
jsr Prompt ; Prompt for next line if in direct mode
asm_r: rts
; Handle Forward Branch
; In cases where the forward branch address is unknown, * may be used as
; the operand for a relative branch instruction. The branch may be resolved
; by entering * on a line by itself, after the address.
HandleFwd: lda IDX_IN ; Where in the line does the * appear?
cmp #$05 ; If it's right after the address, it's for
beq resolve_fw ; resolution of the forward branch point
set_fw: lda EFADDR ; Otherwise, it's to set the forward branch
sta RB_FORWARD ; point. Store the location of the branch
lda EFADDR+1 ; instruction.
sta RB_FORWARD+1 ; ,,
lda #$00 ; Aim the branch instruction at the next
sta RB_OPERAND ; instruction by default
jmp test ; Go back to assemble the instruction
resolve_fw: lda EFADDR ; Compute the relative branch offset from the
sec ; current program counter
sbc RB_FORWARD ; ,,
sec ; Offset by 2 to account for the instruction
sbc #$02 ; ,,
ldy #$01 ; Save the computed offset right after the
sta (RB_FORWARD),y ; original instruction as its operand
ldx #$00 ; Prompt for the same memory location again
jmp Prompt ; ,,
; Error Message
; Invalid opcode or formatting (ASSEMBLY)
; Failed boolean assertion (MISMATCH, borrowed from ROM)
AsmError: lda #<AsmErrMsg ; ?ASSMEBLY
ldx #>AsmErrMsg ; ERROR
bne show_err
MisError: lda #<MISMATCH ; ?MISMATCH
ldx #>MISMATCH ; ERROR
show_err: sta ERROR_PTR ; Set the selected pointer
stx ERROR_PTR+1 ; ,,
jmp CUST_ERR ; And emit the error
; Get Operand
; Populate the operand for an instruction by looking forward in the buffer and
; counting upcoming hex digits.
GetOperand: jsr Buff2Byte ; Get the first byte
bcc getop_r ; If invalid, return
sta OPERAND+1 ; Default to being high byte
jsr Buff2Byte
bcs high_byte ; If an 8-bit operand is provided, move the high
lda OPERAND+1 ; byte to the low byte. Otherwise, just
high_byte: sta OPERAND ; set the low byte with the input
sec ; Compute hypothetical relative branch
sbc EFADDR ; Subtract the program counter address from
sec ; the instruction target
sbc #$02 ; Offset by 2 to account for the instruction
sta RB_OPERAND ; Save the hypothetical relative branch operand
getop_r: rts
; Hypothesis Test
; Search through the language table for each opcode and disassemble it using
; the opcode provided for the candidate instruction. If there's a match, then
; that's the instruction to assemble at the program counter. If Hypotest tries
; all the opcodes without a match, then the candidate instruction is invalid.
Hypotest: jsr ResetLang ; Reset language table
reset: ldy #$06 ; Offset disassembly by 5 bytes for buffer match
sty IDX_OUT ; b/c output buffer will be "$00AC INST"
lda #OPCODE ; Write location to PC for hypotesting
sta EFADDR ; ,,
ldy #$00 ; Set the program counter high byte
sty EFADDR+1 ; ,,
jsr NextInst ; Get next instruction in 6502 table
cmp #TABLE_END ; If we've reached the end of the table,
beq bad_code ; the assembly candidate is no good
sta OPCODE ; Store opcode to hypotesting location
jsr DMnemonic ; Add mnemonic to buffer
ldy #$01 ; Addressing mode is at (LANG_PTR)+1
lda (LANG_PTR),y ; Get addressing mode to pass to DOperand
cmp #RELATIVE ; If the addressing mode is relative, then it's
beq test_rel ; tested separately
jsr DOperand ; Add formatted operand to buffer
lda #$00 ; Add 0 delimiter to end of output buffer so
jsr CharOut ; the match knows when to stop
jsr IsMatch
bcc reset
match: jsr NextValue
lda EFADDR ; Set the INSTSIZE location to the number of
sec ; bytes that need to be programmed
sbc #OPCODE ; ,,
sta INSTSIZE ; ,,
jmp RefreshPC ; Restore the program counter to target address
test_rel: lda #$09 ; Handle relative branch operands here; set
sta IDX_OUT ; a stop after three characters in output
jsr IsMatch ; buffer and check for a match
bcc reset
lda RB_OPERAND ; If the instruction matches, move the relative
sta OPERAND ; branch operand to the working operand
jsr NextValue
jmp match ; Treat this like a regular match from here
bad_code: clc ; Clear carry flag to indicate failure
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MEMORY DUMP COMPONENT
; https://github.com/Chysn/wAx/wiki/3-Memory-Dump
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Memory: ldy #$00
-loop: lda (EFADDR),y
sta CHARDISP,y
jsr Hex
iny
cpy #$04
beq show_char
jsr Space
jmp loop
show_char: lda #RVS_ON ; Reverse on for the characters
jsr CharOut
ldy #$00
-loop: lda CHARDISP,y
and #$7f ; Mask off the high bit for character display;
cmp #QUOTE ; Don't show double quotes
beq alter_char ; ,,
cmp #$20 ; Show everything else at and above space
bcs add_char ; ,,
alter_char: lda #$2e ; Everything else gets a .
add_char: jsr CharOut ; ,,
inc EFADDR
bne next_char
inc EFADDR+1
next_char: iny
cpy #04
bne loop
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ASSERTION TESTER COMPONENT
; https://github.com/Chysn/wAx/wiki/8-Assertion-Tester
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Tester: ldy #$00
-loop: jsr Buff2Byte
bcc test_r ; Bail out on the first non-hex byte
cmp (EFADDR),y
bne test_err
iny
cpy #$04
bne loop
test_r: rts
test_err: jmp MisError
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; BREAKPOINT COMPONENTS
; https://github.com/Chysn/wAx/wiki/7-Breakpoint-Manager
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SetBreak: php
jsr ClearBP ; Clear the old breakpoint, if it exists
plp ; If no breakpoint is chosen (e.g., if ! was)
bcc SetupVec ; by itself), just clear the breakpoint
lda EFADDR ; Add a new breakpoint at the program counter
sta BREAKPOINT ; ,,
lda EFADDR+1 ; ,,
sta BREAKPOINT+1 ; ,,
;ldy #$00 ; (Y is already 0 from ClearBP)
lda (EFADDR),y ; Stash it in the Breakpoint data structure,
sta BREAKPOINT+2 ; to be restored on the next break
tya ; Write BRK to the breakpoint location
sta (EFADDR),y ; ,,
lda #CRSRUP ; Cursor up to overwrite the command
jsr CHROUT ; ,,
ldx #$01 ; List a single line for the user to review
jsr ListLine ; ,,
; Set Up Vectors
; Used by installation, and also by the breakpoint manager
SetupVec: lda #<main ; Intercept GONE to process wedge
sta IGONE ; tool invocations
lda #>main ; ,,
sta IGONE+1 ; ,,
lda #<Break ; Set the BRK interrupt vector
sta CBINV ; ,,
lda #>Break ; ,,
sta CBINV+1 ; ,,
rts
; BRK Trapper
; Replaces the default BRK handler. Gets registers from hardware interrupt
; and puts them in the SYS register storage locations. Gets program counter
; and stores it in the persistent counter location. Then falls through
; to register display.
Break: pla ; Get values from stack and put them in the
tay ; proper registers
pla ; ,,
tax ; ,,
pla ; ,,
plp ; Get the processor status
cld ; Escape hatch for accidentally-set Decimal flag
jsr SYS_TAIL ; Store regiters in SYS locations
pla ; Get Program Counter from interrupt and put
sta SYS_DEST ; it in the persistent counter
pla ; ,,
sta SYS_DEST+1 ; ,,
lda #"*"
jsr CHROUT
jsr RegDisp ; Show the register display
jmp (WARM_START)
; Clear Breakpoint
; Restore breakpoint byte and zero out breakpoint data
ClearBP: lda BREAKPOINT ; Get the breakpoint
sta CHARAC ; Stash it in a zeropage location
lda BREAKPOINT+1 ; ,,
sta CHARAC+1 ; ,,
ldy #$00
lda (CHARAC),y ; What's currently at the Breakpoint?
bne bp_reset ; If it's not a BRK, then preserve what's there
lda BREAKPOINT+2 ; Otherwise, get the breakpoint byte and
sta (CHARAC),y ; put it back
bp_reset: sty BREAKPOINT ; And then clear out the whole
sty BREAKPOINT+1 ; breakpoint data structure
sty BREAKPOINT+2 ; ,,
rts
; Breakpoint Indicator
; Also restores the breakpoint byte, temporarily
BreakInd: ldy #$00 ; Is this a BRK instruction?
lda (EFADDR),y ; ,,
bne ind_r ; If not, do nothing
lda BREAKPOINT ; If it is a BRK, is it our breakpoint?
cmp EFADDR ; ,,
bne ind_r ; ,,
lda BREAKPOINT+1 ; ,,
cmp EFADDR+1 ; ,,
bne ind_r ; ,,
lda #RVS_ON ; Reverse on for the breakpoint
jsr CharOut
lda BREAKPOINT+2 ; Temporarily restore the breakpoint byte
sta (EFADDR),y ; for disassembly purposes
ind_r: rts
; Enable Breakpoint
; Used after disassembly, in case the BreakInd turned the breakpoint off
EnableBP: lda BREAKPOINT+2
beq enable_r
lda BREAKPOINT
sta CHARAC
lda BREAKPOINT+1
sta CHARAC+1
ldy #$00 ; Write BRK to the breakpoint
tya ; ,,
sta (CHARAC),y ; ,,
enable_r: rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; REGISTER COMPONENTS
; https://github.com/Chysn/wAx/wiki/Register-Editor
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Register: jsr ResetIn
jsr Buff2Byte
bcc RegDisp
sta ACC
jsr Buff2Byte
bcc register_r
sta XREG
jsr Buff2Byte
bcc register_r
sta YREG
jsr Buff2Byte
bcc register_r
sta PROC
register_r: rts
; Register Display
RegDisp: lda #$00
sta IDX_OUT
lda #<Registers ; Print register display bar
ldy #>Registers ; ,,
jsr PrintStr ; ,,
ldy #$00 ; Get registers' values from storage and add
-loop: lda ACC,y ; each one to the buffer. These values came
jsr Hex ; from the hardware IRQ, and are A,X,Y,P
jsr Space ; ,,
iny ; ,,
cpy #$04 ; ,,
bne loop ; ,,
tsx ; Add stack pointer to the buffer
txa ; ,,
jsr Hex ; ,,
jsr Space ; ,,
lda SYS_DEST+1 ; Print high byte of SYS destination
jsr Hex ; ,,
lda SYS_DEST ; Print low byte of SYS destination
jsr Hex ; ,,
jmp PrintBuff ; Print the buffer
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; SUBROUTINE EXECUTION COMPONENT
; https://github.com/Chysn/wAx/wiki/Subroutine-Execution
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Execute: bcc iterate ; No address was provided; continue from BRKpt
lda EFADDR ; Set the temporary INT storage to the program
sta SYS_DEST ; counter. This is what SYS uses for its
lda EFADDR+1 ; execution address, and I'm using that
sta SYS_DEST+1 ; system to borrow saved Y,X,A,P values
lda #>RegDisp-1 ; Add the register display return address to
pha ; the stack, as the return point after the
lda #<RegDisp-1 ; SYS tail
pha ; ,,
jsr SetupVec ; Make sure the BRK handler is enabled
jmp SYS ; Call BASIC SYS, after the parameter parsing
iterate: pla ; Remove return to Return from the stack; it
pla ; is not needed
jmp SYS_BRK ; SYS with no tail return address
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MEMORY SAVE COMPONENT
; https://github.com/Chysn/wAx/wiki/9-Memory-Save
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MemSave: bcc save_err ; Bail if the address is no good
jsr Buff2Byte ; Convert 2 characters to a byte
bcc save_err ; Fail if the byte couldn't be parsed
sta WORK+1 ; Save to the EFADDR high byte
jsr Buff2Byte ; Convert next 2 characters to byte
bcc save_err ; Fail if the byte couldn't be parsed
sta WORK ; Save to the EFADDR low byte
jsr DiskSetup ; SETLFS, get filename length, etc.
ldx #<INBUFFER+8 ; ,,
ldy #>INBUFFER+8 ; ,,
jsr SETNAM ; ,,
lda #EFADDR ; Set up SAVE call
ldx WORK ; ,,
ldy WORK+1 ; ,,
jsr SAVE ; ,,
bcs DiskError
jmp Linefeed
save_err: jmp SYNTAX_ERR ; To ?SYNTAX ERROR
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MEMORY LOAD COMPONENT
; https://github.com/Chysn/wAx/wiki/9-Memory-Save-Load
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MemLoad: jsr ResetIn ; Reset the input buffer index because there's
jsr DiskSetup ; SETLFS, get filename length, etc.
ldx #<INBUFFER ; Set location of filename
ldy #>INBUFFER ; ,,
jsr SETNAM ; ,,
lda #$00 ; Perform Load
;ldx #$ff ; ,, (X and Y don't matter because the secondary
;ldy #$ff ; ,, address indicates use of header)
jsr LOAD ; ,,
bcs DiskError
jmp Linefeed
; Disk Setup
; Clear breakpoint, set up logical file, get filename length, return in A
; for call to SETNAM
DiskSetup: jsr ClearBP ; Clear breakpoint
lda #$42 ; Set up logical file
ldx #DEVICE ; ,,
ldy #$01 ; ,, Specify use of header for address
jsr SETLFS ; ,,
ldy #$00
-loop: jsr CharGet
beq setup_r
iny
cpy #$08
bne loop
setup_r: tya
rts
; Show System Disk Error
DiskError: jmp ERROR_NO
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; SUBROUTINES
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Look up opcode
Lookup: sta INSTDATA ; INSTDATA is the found opcode
jsr ResetLang ; Reset the language table reference
-loop: jsr NextInst ; Get the next 6502 instruction in the table
cmp #TABLE_END ; If we've reached the end of the table,
beq not_found ; then the instruction is invalid
cmp INSTDATA ; If the instruction doesn't match the opcode,
bne loop ; keep searching.
found: iny
lda (LANG_PTR),y ; A match was found! Set the addressing mode
sta INSTDATA+1 ; to the instruction data structure
sec ; and set the carry flag to indicate success
rts
not_found: clc ; Reached the end of the language table without
rts ; finding a matching instruction
; Reset Language Table
ResetLang: lda #<InstrSet-2 ; Start two bytes before the Instruction Set
sta LANG_PTR ; table, because advancing the table will be
lda #>InstrSet-2 ; an early thing we do
sta LANG_PTR+1 ; ,,
rts
; Next Instruction in Language Table
; Handle mnemonics by recording the last found mnemonic and then advancing
; to the following instruction. The opcode is returned in A.
NextInst: lda #$02 ; Each language entry is two bytes. Advance to
clc ; the next entry in the table
adc LANG_PTR ; ,,
sta LANG_PTR ; ,,
bcc ch_mnem ; ,,
inc LANG_PTR+1 ; ,,
ch_mnem: ldy #$01 ; Is this entry an instruction record?
lda (LANG_PTR),y ; ,,
and #$01 ; ,,
beq adv_lang_r ; If it's an instruction, return
lda (LANG_PTR),y ; Otherwise, set the mnemonic in the workspace
sta MNEM+1 ; as two bytes, five bits per character for
dey ; three characters. See the 6502 table for
lda (LANG_PTR),y ; a description of the data encoding
sta MNEM ; ,,
jmp NextInst ; Go to what should now be an instruction
adv_lang_r: ldy #$00 ; When an instruction is found, set A to its
lda (LANG_PTR),y ; opcode and return
rts
; Get Character
; Akin to CHRGET, but scans the INBUFFER, which has already been detokenized
CharGet: ldx IDX_IN
lda INBUFFER,x
php
inc IDX_IN
plp
rts
; Buffer to Byte
; Get two characters from the buffer and evaluate them as a hex byte
Buff2Byte: jsr CharGet
jsr Char2Nyb
bcc not_found ; See Lookup subroutine above
asl ; Multiply high nybble by 16
asl ; ,,
asl ; ,,
asl ; ,,
sta WORK
jsr CharGet
jsr Char2Nyb
bcc buff2_r ; Clear Carry flag indicates invalid hex
ora WORK ; Combine high and low nybbles
;sec ; Set Carry flag indicates success
buff2_r: rts
; Is Buffer Match
; Does the input buffer match the output buffer?
; Carry is set if there's a match, clear if not
IsMatch: ldy #$06 ; Offset for character after address
-loop: lda OUTBUFFER,y ; Compare the assembly with the disassembly
cmp INBUFFER-2,y ; in the buffers
bne not_found ; See Lookup subroutine above
iny
cpy IDX_OUT
bne loop ; Loop until the buffer is done
sec ; This matches; set carry
rts
; Character to Nybble
; A is the character in the text buffer to be converted into a nybble
Char2Nyb: cmp #"9"+1 ; Is the character in range 0-9?
bcs not_digit ; ,,
cmp #"0" ; ,,
bcc not_digit ; ,,
sbc #"0" ; If so, nybble value is 0-9
rts
not_digit: cmp #"F"+1 ; Is the character in the range A-F?
bcs not_found ; See Lookup subroutine above
cmp #"A"
bcc not_found ; See Lookup subroutine above
sbc #"A"-$0a ; The nybble value is 10-15
rts
; Next Program Counter
; Advance Program Counter by one byte, and return its value
NextValue: inc EFADDR
bne next_r
inc EFADDR+1
next_r: ldy #$00
lda (EFADDR),y
rts
; Commonly-Used Characters
CloseParen: lda #")"
.byte $3c ; TOP (skip word)
Comma: lda #","
.byte $3c ; TOP (skip word)
Space: lda #" "
.byte $3c ; TOP (skip word)
HexPrefix: lda #"$"
; Fall through to CharOut
; Character to Output
; Add the character in A to the outut byffer
CharOut: sta CHARAC ; Save temporary character
tya ; Save registers
pha ; ,,
txa ; ,,
pha ; ,,
ldx IDX_OUT ; Write to the next OUTBUFFER location
lda CHARAC ; ,,
sta OUTBUFFER,x ; ,,
inc IDX_OUT ; ,,
pla ; Restore registers
tax ; ,,
pla ; ,,
tay ; ,,
write_r: rts
; Write hexadecimal character
Hex: pha ; Hex converter based on from WOZ Monitor,
lsr ; Steve Wozniak, 1976
lsr
lsr
lsr
jsr prhex
pla
prhex: and #$0f
ora #"0"
cmp #"9"+1
bcc echo
adc #$06
echo: jmp CharOut
; Show 8-bit Parameter
Param_8: jsr HexPrefix
jsr NextValue
jmp Hex
; Show 16-Bit Parameter
Param_16: jsr HexPrefix
jsr NextValue
pha
jsr NextValue
jsr Hex
pla
jmp Hex
; Transcribe to Buffer
; Get a character from the input buffer and transcribe it to the
; input buffer. If the character is a BASIC token, then possibly
; explode it into individual characters.
Transcribe: jsr CHRGET ; Get character from input buffer
cmp #$00 ; If it's 0, then quit transcribing and return
beq xscribe_r ; ,,
cmp #QUOTE ; If a quote is found, modify CHRGET so that
bne ch_token ; spaces are no longer filtered out
lda #$06 ; $0082 BEQ $0073 -> BEQ $008a
sta $83 ; ,,
lda #QUOTE ; Put quote back so it can be added to buffer
ch_token: cmp #$80 ; Is the character in A a BASIC token?
bcc x_add ; If it's not a token, just add it to buffer
ldy $83 ; If it's a token, check the CHRGET routine
cpy #$06 ; and skip detokenization if it's been
beq x_add ; modified.
jsr Detokenize ; Detokenize and continue transciption
jmp Transcribe ; ,, (Carry is always set by Detokenize)
x_add: jsr AddInput ; Add the text to the buffer
jmp Transcribe ; (Carry is always set by AddInput)
xscribe_r: jmp AddInput ; Add the final zero, and fix CHRGET...
; Reset Input Buffer
ResetIn: lda #$00
sta IDX_IN
rts
; Add Input
; Add a character to the input buffer and advance the counter
AddInput: ldx IDX_IN
cpx #$16 ; Wedge lines are limited to the physical
bcs add_r ; line length
sta INBUFFER,x
inc IDX_IN
add_r: rts
; Detokenize
; If a BASIC token is found, explode that token into PETSCII characters
; so it can be disassembled. This is based on the ROM uncrunch code around $c71a
Detokenize: ldy #$65
tax ; Copy token number to X
get_next: dex
beq explode ; Token found, go write
-loop iny ; Else increment index
lda KEYWORDS,y ; Get byte from keyword table
bpl loop ; Loop until end marker
bmi get_next
explode: iny ; Found the keyword; get characters from
lda KEYWORDS,y ; table
bmi last_char ; If there's an end marker, mask byte and
jsr AddInput ; add to input buffer
bne explode
last_char: and #$7f ; Take out bit 7 and
jmp AddInput ; add to input buffer
; Print Buffer
; Add a $00 delimiter to the end of the output buffer, and print it out
PrintBuff: lda #$00 ; End the buffer with 0
jsr CharOut ; ,,
lda #<OUTBUFFER ; Print the line
ldy #>OUTBUFFER ; ,,
jsr PrintStr ; ,,
lda #RVS_OFF ; Reverse off after each line
jsr CHROUT ; ,,
; Fall through to Linefeed
Linefeed: lda #LF
jmp CHROUT
; Print String
; Like BASIC's $cb1e, but not destructive to BASIC memory when coming from
; the BASIC input buffer (see $d4bb)
PrintStr: sta CHARAC
sty CHARAC+1
ldy #$00
-loop: lda (CHARAC),y
beq print_r
jsr CHROUT
lda #$00 ; Turn off quote mode for each character
sta $d4 ; ,,
iny
bne loop
print_r: rts
; Prompt for Next Line
; X should be set to the number of bytes the program counter should be
; advanced
Prompt: jsr DirectMode ; If a tool is in Direct Mode, increase
bne prompt_r ; the PC by the size of the instruction
tya ; and write it to the keyboard buffer (by
sta IDX_OUT ; way of populating the output buffer)
lda TOOL_CHR ; ,,
jsr CharOut ; ,,
txa ; ,,
clc ; ,,
adc EFADDR ; ,,
sta EFADDR ; ,,
tya ; ,, (Y is still $00, otherwise lda #$00)
adc EFADDR+1 ; ,,
jsr Hex ; ,,
lda EFADDR ; ,,
jsr Hex ; ,,
lda #CRSRRT ; ,,
jsr CharOut ; ,,
;ldy #$00 ; (Y is still $00 from above)
-loop: lda OUTBUFFER,y ; Copy the output buffer into KEYBUFF, which
sta KEYBUFF,y ; will simulate user entry
iny ; ,,
cpy #$06 ; ,,
bne loop ; ,,
sty KBSIZE ; Setting the buffer size will make it go
prompt_r: rts
; In Direct Mode
; If the wAx tool is running in Direct Mode, the Zero flag will be set
DirectMode: ldy CURLIN+1
iny
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; DATA
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ToolTable contains the list of tools and addresses for each tool
ToolTable: .byte T_DIS,T_ASM,T_MEM,T_REG,T_EXE,T_BRK,T_TST,T_SAV,T_LOA
ToolAddr_L: .byte <List-1,<Assemble-1,<List-1,<Register-1,<Execute-1
.byte <SetBreak-1,<Tester-1,<MemSave-1,<MemLoad-1
ToolAddr_H: .byte >List-1,>Assemble-1,>List-1,>Register-1,>Execute-1
.byte >SetBreak-1,>Tester-1,>MemSave-1,>MemLoad-1
; Text display tables
Intro: .asc LF,"2K WAX ON",LF,$00
Registers: .asc LF,$b0,"Y",$c0,$c0,"X",$c0,$c0,"A",$c0,$c0
.asc "P",$c0,$c0,"S",$c0,$c0,"PC",$c0,$c0,LF,";",$00
AsmErrMsg: .asc "ASSEMBL",$d9
; Instruction Set
; This table contains two types of one-word records--mnemonic records and
; instruction records. Every word in the table is in big-endian format, so
; the high byte is first.
;
; Mnemonic records are formatted like this...
; fffffsss ssttttt1
; where f is first letter, s is second letter, and t is third letter. Bit
; 0 of the word is set to 1 to identify this word as a mnemonic record.
;
; Each mnemonic record has one or more instruction records after it.
; Instruction records are formatted like this...
; oooooooo aaaaaaa0
; where o is the opcode and a is the addressing mode (see Constants section
; at the top of the code). Bit 0 of the word is set to 0 to identify this
; word as an instruction record.
InstrSet: .byte $09,$07 ; ADC
.byte $69,$a0 ; * ADC #immediate
.byte $65,$70 ; * ADC zeropage
.byte $75,$80 ; * ADC zeropage,X
.byte $6d,$40 ; * ADC absolute
.byte $7d,$50 ; * ADC absolute,X
.byte $79,$60 ; * ADC absolute,Y
.byte $61,$20 ; * ADC (indirect,X)
.byte $71,$30 ; * ADC (indirect),Y
.byte $0b,$89 ; AND
.byte $29,$a0 ; * AND #immediate
.byte $25,$70 ; * AND zeropage
.byte $35,$80 ; * AND zeropage,X
.byte $2d,$40 ; * AND absolute
.byte $3d,$50 ; * AND absolute,X
.byte $39,$60 ; * AND absolute,Y
.byte $21,$20 ; * AND (indirect,X)
.byte $31,$30 ; * AND (indirect),Y
.byte $0c,$d9 ; ASL
.byte $0a,$b0 ; * ASL accumulator
.byte $06,$70 ; * ASL zeropage
.byte $16,$80 ; * ASL zeropage,X
.byte $0e,$40 ; * ASL absolute
.byte $1e,$50 ; * ASL absolute,X
.byte $10,$c7 ; BCC
.byte $90,$c0 ; * BCC relative
.byte $10,$e7 ; BCS
.byte $b0,$c0 ; * BCS relative
.byte $11,$63 ; BEQ
.byte $f0,$c0 ; * BEQ relative
.byte $12,$69 ; BIT
.byte $24,$70 ; * BIT zeropage
.byte $2c,$40 ; * BIT absolute
.byte $13,$53 ; BMI
.byte $30,$c0 ; * BMI relative
.byte $13,$8b ; BNE
.byte $d0,$c0 ; * BNE relative
.byte $14,$19 ; BPL
.byte $10,$c0 ; * BPL relative
.byte $14,$97 ; BRK
.byte $00,$b0 ; * BRK implied
.byte $15,$87 ; BVC
.byte $50,$c0 ; * BVC relative
.byte $15,$a7 ; BVS
.byte $70,$c0 ; * BVS relative
.byte $1b,$07 ; CLC
.byte $18,$b0 ; * CLC implied
.byte $1b,$09 ; CLD
.byte $d8,$b0 ; * CLD implied
.byte $1b,$13 ; CLI
.byte $58,$b0 ; * CLI implied
.byte $1b,$2d ; CLV
.byte $b8,$b0 ; * CLV implied
.byte $1b,$61 ; CMP
.byte $c9,$a0 ; * CMP #immediate
.byte $c5,$70 ; * CMP zeropage
.byte $d5,$80 ; * CMP zeropage,X
.byte $cd,$40 ; * CMP absolute
.byte $dd,$50 ; * CMP absolute,X
.byte $d9,$60 ; * CMP absolute,Y
.byte $c1,$20 ; * CMP (indirect,X)
.byte $d1,$30 ; * CMP (indirect),Y
.byte $1c,$31 ; CPX
.byte $e0,$a0 ; * CPX #immediate
.byte $e4,$70 ; * CPX zeropage
.byte $ec,$40 ; * CPX absolute
.byte $1c,$33 ; CPY
.byte $c0,$a0 ; * CPY #immediate
.byte $c4,$70 ; * CPY zeropage
.byte $cc,$40 ; * CPY absolute
.byte $21,$47 ; DEC
.byte $c6,$70 ; * DEC zeropage
.byte $d6,$80 ; * DEC zeropage,X
.byte $ce,$40 ; * DEC absolute
.byte $de,$50 ; * DEC absolute,X
.byte $21,$71 ; DEX
.byte $ca,$b0 ; * DEX implied
.byte $21,$73 ; DEY
.byte $88,$b0 ; * DEY implied
.byte $2b,$e5 ; EOR
.byte $49,$a0 ; * EOR #immediate
.byte $45,$70 ; * EOR zeropage
.byte $55,$80 ; * EOR zeropage,X
.byte $4d,$40 ; * EOR absolute
.byte $5d,$50 ; * EOR absolute,X
.byte $59,$60 ; * EOR absolute,Y
.byte $41,$20 ; * EOR (indirect,X)
.byte $51,$30 ; * EOR (indirect),Y
.byte $4b,$87 ; INC
.byte $e6,$70 ; * INC zeropage
.byte $f6,$80 ; * INC zeropage,X
.byte $ee,$40 ; * INC absolute
.byte $fe,$50 ; * INC absolute,X
.byte $4b,$b1 ; INX
.byte $e8,$b0 ; * INX implied
.byte $4b,$b3 ; INY
.byte $c8,$b0 ; * INY implied
.byte $53,$61 ; JMP
.byte $4c,$40 ; * JMP absolute
.byte $6c,$10 ; * JMP indirect
.byte $54,$e5 ; JSR
.byte $20,$40 ; * JSR absolute
.byte $61,$03 ; LDA
.byte $a9,$a0 ; * LDA #immediate
.byte $a5,$70 ; * LDA zeropage
.byte $b5,$80 ; * LDA zeropage,X
.byte $ad,$40 ; * LDA absolute
.byte $bd,$50 ; * LDA absolute,X
.byte $b9,$60 ; * LDA absolute,Y
.byte $a1,$20 ; * LDA (indirect,X)
.byte $b1,$30 ; * LDA (indirect),Y
.byte $61,$31 ; LDX
.byte $a2,$a0 ; * LDX #immediate
.byte $a6,$70 ; * LDX zeropage
.byte $b6,$90 ; * LDX zeropage,Y
.byte $ae,$40 ; * LDX absolute
.byte $be,$60 ; * LDX absolute,Y
.byte $61,$33 ; LDY
.byte $a0,$a0 ; * LDY #immediate
.byte $a4,$70 ; * LDY zeropage
.byte $b4,$80 ; * LDY zeropage,X
.byte $ac,$40 ; * LDY absolute
.byte $bc,$50 ; * LDY absolute,X
.byte $64,$e5 ; LSR
.byte $4a,$b0 ; * LSR accumulator
.byte $46,$70 ; * LSR zeropage
.byte $56,$80 ; * LSR zeropage,X
.byte $4e,$40 ; * LSR absolute
.byte $5e,$50 ; * LSR absolute,X
.byte $73,$e1 ; NOP
.byte $ea,$b0 ; * NOP implied
.byte $7c,$83 ; ORA
.byte $09,$a0 ; * ORA #immediate
.byte $05,$70 ; * ORA zeropage
.byte $15,$80 ; * ORA zeropage,X
.byte $0d,$40 ; * ORA absolute
.byte $1d,$50 ; * ORA absolute,X
.byte $19,$60 ; * ORA absolute,Y
.byte $01,$20 ; * ORA (indirect,X)
.byte $11,$30 ; * ORA (indirect),Y
.byte $82,$03 ; PHA
.byte $48,$b0 ; * PHA implied
.byte $82,$21 ; PHP
.byte $08,$b0 ; * PHP implied
.byte $83,$03 ; PLA
.byte $68,$b0 ; * PLA implied
.byte $83,$21 ; PLP
.byte $28,$b0 ; * PLP implied
.byte $93,$d9 ; ROL
.byte $2a,$b0 ; * ROL accumulator
.byte $26,$70 ; * ROL zeropage
.byte $36,$80 ; * ROL zeropage,X
.byte $2e,$40 ; * ROL absolute
.byte $3e,$50 ; * ROL absolute,X
.byte $93,$e5 ; ROR
.byte $6a,$b0 ; * ROR accumulator
.byte $66,$70 ; * ROR zeropage
.byte $76,$80 ; * ROR zeropage,X
.byte $6e,$40 ; * ROR absolute
.byte $7e,$50 ; * ROR absolute,X
.byte $95,$13 ; RTI
.byte $40,$b0 ; * RTI implied
.byte $95,$27 ; RTS
.byte $60,$b0 ; * RTS implied
.byte $98,$87 ; SBC
.byte $e9,$a0 ; * SBC #immediate
.byte $e5,$70 ; * SBC zeropage
.byte $f5,$80 ; * SBC zeropage,X
.byte $ed,$40 ; * SBC absolute
.byte $fd,$50 ; * SBC absolute,X
.byte $f9,$60 ; * SBC absolute,Y
.byte $e1,$20 ; * SBC (indirect,X)
.byte $f1,$30 ; * SBC (indirect),Y
.byte $99,$47 ; SEC
.byte $38,$b0 ; * SEC implied
.byte $99,$49 ; SED
.byte $f8,$b0 ; * SED implied
.byte $99,$53 ; SEI
.byte $78,$b0 ; * SEI implied
.byte $9d,$03 ; STA
.byte $85,$70 ; * STA zeropage
.byte $95,$80 ; * STA zeropage,X
.byte $8d,$40 ; * STA absolute
.byte $9d,$50 ; * STA absolute,X
.byte $99,$60 ; * STA absolute,Y
.byte $81,$20 ; * STA (indirect,X)
.byte $91,$30 ; * STA (indirect),Y
.byte $9d,$31 ; STX
.byte $86,$70 ; * STX zeropage
.byte $96,$90 ; * STX zeropage,Y
.byte $8e,$40 ; * STX absolute
.byte $9d,$33 ; STY
.byte $84,$70 ; * STY zeropage
.byte $94,$80 ; * STY zeropage,X
.byte $8c,$40 ; * STY absolute
.byte $a0,$71 ; TAX
.byte $aa,$b0 ; * TAX implied
.byte $a0,$73 ; TAY
.byte $a8,$b0 ; * TAY implied
.byte $a4,$f1 ; TSX
.byte $ba,$b0 ; * TSX implied
.byte $a6,$03 ; TXA
.byte $8a,$b0 ; * TXA implied
.byte $a6,$27 ; TXS
.byte $9a,$b0 ; * TXS implied
.byte $a6,$43 ; TYA
.byte $98,$b0 ; * TYA implied
Expand: .byte TABLE_END,$00 ; End of 6502 table |
; A122074: a(0)=1, a(1)=6, a(n) = 7*a(n-1) - 2*a(n-2).
; 1,6,40,268,1796,12036,80660,540548,3622516,24276516,162690580,1090281028,7306586036,48965540196,328145609300,2199088184708,14737326074356,98763106151076,661867090908820,4435543424059588,29725069786599476,199204401658077156,1334980672033341140,8946455900917233668,59955229962353953396,401793697934643206436,2692645425617794538260,18044930583455275354948,120929223232951338408116,810414701463748818146916,5431044463780339050212180,36396481843534875715191428,243913283977183451905915636,1634600024153214411911026596,10954373601118133979565354900,73411415159520509033135431108,491971158914407295272817307956,3296975282081810048843450293476,22094884656743855751358517438420,148070242033043370161822721481988,992301924917815879630042015497076,6649972990358624417086648665515556,44565207082674739160346456627614740,298656503598005925288251899062272068
mov $1,1
lpb $0
sub $0,1
mul $1,2
add $2,$1
add $2,$1
add $1,$2
lpe
mov $0,$1
|
; see engine/naming_screen.asm
MailEntry_Uppercase:
db "A B C D E F G H I J"
db "K L M N O P Q R S T"
db "U V W X Y Z , ? !"
db "1 2 3 4 5 6 7 8 9 0"
db "<PK> <MN> <PO> <KE> é ♂ ♀ ¥ … ×"
db "lower DEL END "
MailEntry_Lowercase:
db "a b c d e f g h i j"
db "k l m n o p q r s t"
db "u v w x y z . - /"
db "'d 'l 'm 'r 's 't 'v & ( )"
db "“ ” [ ] ' : ; "
db "UPPER DEL END "
|
; A136437: a(n) = prime(n) - k! where k is the greatest number such that k! <= prime(n).
; 0,1,3,1,5,7,11,13,17,5,7,13,17,19,23,29,35,37,43,47,49,55,59,65,73,77,79,83,85,89,7,11,17,19,29,31,37,43,47,53,59,61,71,73,77,79,91,103,107,109,113,119,121,131,137,143,149,151,157,161,163,173,187,191,193,197,211,217,227,229,233,239,247,253,259,263,269,277,281,289,299,301,311,313,319,323,329,337,341,343,347,359,367,371,379,383,389,401,403,421
seq $0,40 ; The prime numbers.
sub $0,1
seq $0,212598 ; a(n) = n - m!, where m is the largest number such that m! <= n.
|
BITS 32
;TEST_FILE_META_BEGIN
;TEST_TYPE=TEST_F
;TEST_IGNOREFLAGS=FLAG_AF
;TEST_FILE_META_END
; TEST8ri
mov ah, 0x2
;TEST_BEGIN_RECORDING
test ah, 0x3
;TEST_END_RECORDING
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x826a, %rsi
lea addresses_D_ht+0x1166a, %rdi
nop
nop
nop
nop
nop
and $33592, %r9
mov $125, %rcx
rep movsq
nop
nop
nop
nop
nop
sub $69, %r9
lea addresses_D_ht+0xe1ca, %r10
nop
nop
add $52863, %rbx
movb $0x61, (%r10)
nop
and %rsi, %rsi
lea addresses_normal_ht+0x986a, %rsi
nop
nop
nop
inc %rbx
movb (%rsi), %r10b
sub %rcx, %rcx
lea addresses_WC_ht+0x180b4, %rsi
lea addresses_WC_ht+0x5e8a, %rdi
clflush (%rdi)
nop
nop
sub %rdx, %rdx
mov $47, %rcx
rep movsw
nop
nop
nop
nop
nop
cmp $33047, %rcx
lea addresses_WC_ht+0x37d7, %rdx
nop
nop
nop
add $59546, %rax
movb (%rdx), %r10b
and $26008, %rsi
lea addresses_A_ht+0x60aa, %rbx
nop
nop
nop
xor $1817, %rax
vmovups (%rbx), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $1, %xmm0, %rcx
nop
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_WT_ht+0x29ea, %rsi
lea addresses_D_ht+0xe37a, %rdi
nop
nop
sub $14298, %r10
mov $119, %rcx
rep movsw
nop
nop
nop
nop
xor %rbx, %rbx
lea addresses_UC_ht+0x103cf, %rbx
nop
nop
nop
nop
sub $1206, %r9
mov (%rbx), %ax
nop
nop
nop
nop
sub $23771, %rdx
lea addresses_A_ht+0xe66a, %rdi
nop
nop
nop
nop
add %rbx, %rbx
mov (%rdi), %cx
nop
nop
nop
nop
xor %r9, %r9
lea addresses_UC_ht+0xec6a, %rdi
nop
nop
nop
nop
nop
xor %r9, %r9
movw $0x6162, (%rdi)
nop
nop
nop
nop
and %rsi, %rsi
lea addresses_A_ht+0x4d6a, %rsi
nop
nop
nop
nop
nop
inc %rdx
movups (%rsi), %xmm3
vpextrq $1, %xmm3, %rdi
xor %rdi, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r14
push %rax
push %rbp
push %rcx
// Store
lea addresses_WC+0x89aa, %r10
nop
nop
nop
nop
nop
dec %rbp
movl $0x51525354, (%r10)
nop
nop
nop
nop
sub $43560, %rax
// Store
lea addresses_A+0x36ae, %rcx
nop
and %r11, %r11
movl $0x51525354, (%rcx)
cmp %rcx, %rcx
// Load
lea addresses_normal+0x1d9d2, %rax
nop
nop
nop
nop
and %r11, %r11
mov (%rax), %ebp
nop
and %r12, %r12
// Store
mov $0x980f8000000026a, %rbp
nop
nop
add %rax, %rax
mov $0x5152535455565758, %r10
movq %r10, %xmm5
movups %xmm5, (%rbp)
nop
nop
nop
nop
nop
sub %r10, %r10
// Load
lea addresses_UC+0xab6a, %r11
cmp $30900, %rbp
movb (%r11), %al
nop
nop
nop
and $34524, %r10
// Store
lea addresses_UC+0x1920a, %r10
nop
nop
nop
add $28345, %rcx
movb $0x51, (%r10)
nop
nop
xor $37347, %rbp
// Faulty Load
lea addresses_WC+0x646a, %rcx
nop
nop
nop
nop
nop
xor $28714, %r12
mov (%rcx), %r14d
lea oracles, %rax
and $0xff, %r14
shlq $12, %r14
mov (%rax,%r14,1), %r14
pop %rcx
pop %rbp
pop %rax
pop %r14
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': True, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': True, 'type': 'addresses_WC', 'same': False, 'AVXalign': True, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_A', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': True, 'congruent': 5}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': True, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 9}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 1}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 5}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_WT_ht', 'congruent': 7}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 4}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': True, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': True, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
#include "hyperparameter_tuning.h"
#include <catboost/private/libs/algo/data.h>
#include <catboost/private/libs/algo/approx_dimension.h>
#include <catboost/libs/data/feature_names_converter.h>
#include <catboost/libs/data/objects_grouping.h>
#include <catboost/libs/helpers/cpu_random.h>
#include <catboost/libs/helpers/exception.h>
#include <catboost/libs/helpers/dynamic_iterator.h>
#include <catboost/libs/loggers/catboost_logger_helpers.h>
#include <catboost/libs/loggers/logger.h>
#include <catboost/libs/logging/logging.h>
#include <catboost/libs/logging/profile_info.h>
#include <catboost/libs/train_lib/dir_helper.h>
#include <catboost/private/libs/options/plain_options_helper.h>
#include <util/generic/algorithm.h>
#include <util/generic/deque.h>
#include <util/generic/set.h>
#include <util/generic/xrange.h>
#include <util/random/shuffle.h>
#include <numeric>
namespace {
const TVector<TString> NanModeParamAliaces {"nan_mode"};
const TVector<TString> BorderCountParamAliaces {"border_count", "max_bin"};
const TVector<TString> BorderTypeParamAliaces {"feature_border_type"};
constexpr ui32 IndexOfFirstTrainingParameter = 3;
// TEnumeratedSet - type of sets, TValue - type of values in sets
// Set should have access to elements by index and size() method
// Uniqueness of elements is not required: 'set' is just unformal term
template <class TEnumeratedSet, class TValue>
class TProductIteratorBase: public NCB::IDynamicIterator<TConstArrayRef<TValue>> {
protected:
bool IsStopIteration = false;
size_t FirstVaryingDigit = 0;
ui64 PassedElementsCount = 0;
ui64 TotalElementsCount;
TVector<size_t> MultiIndex;
TVector<TEnumeratedSet> Sets;
TVector<TValue> State;
protected:
explicit TProductIteratorBase(const TVector<TEnumeratedSet>& sets)
: Sets(sets) {
InitClassFields(sets);
ui64 totalCount = 1;
ui64 logTotalCount = 0;
for (const auto& set : sets) {
CB_ENSURE(set.size() > 0, "Error: set should be not empty");
logTotalCount += log2(set.size());
CB_ENSURE(logTotalCount < 64, "Error: The parameter grid is too large. Try to reduce it.");
totalCount *= set.size();
}
TotalElementsCount = totalCount;
}
void InitClassFields(const TVector<TEnumeratedSet>& sets) {
if (sets.size() == 0) {
IsStopIteration = true;
return;
}
MultiIndex.resize(sets.size(), 0);
size_t idx = 0;
for (const auto& set : sets) {
State.push_back(set[0]);
MultiIndex[idx] = set.size() - 1;
++idx;
}
}
const TVector<TValue>& NextWithOffset(ui64 offset) {
for (size_t setIdx = MultiIndex.size() - 1; setIdx > 0; --setIdx) {
size_t oldDigit = MultiIndex[setIdx];
MultiIndex[setIdx] = (MultiIndex[setIdx] + offset) % Sets[setIdx].size();
State[setIdx] = Sets[setIdx][MultiIndex[setIdx]];
if (oldDigit + offset < Sets[setIdx].size()) {
return State;
}
offset = (offset - (Sets[setIdx].size() - oldDigit)) / Sets[setIdx].size() + 1;
}
MultiIndex[0] = (MultiIndex[0] + offset) % Sets[0].size();
State[0] = Sets[0][MultiIndex[0]];
return State;
}
bool IsIteratorReachedEnd() {
return PassedElementsCount >= TotalElementsCount;
}
public:
ui64 GetTotalElementsCount() {
return TotalElementsCount;
}
};
template <class TEnumeratedSet, class TValue>
class TCartesianProductIterator: public TProductIteratorBase<TEnumeratedSet, TValue> {
public:
explicit TCartesianProductIterator(const TVector<TEnumeratedSet>& sets)
: TProductIteratorBase<TEnumeratedSet, TValue>(sets)
{}
virtual bool Next(TConstArrayRef<TValue>* value) override {
if (this->IsIteratorReachedEnd()) {
return false;
}
this->PassedElementsCount++;
*value = this->NextWithOffset(1);
return true;
}
};
template <class TEnumeratedSet, class TValue>
class TRandomizedProductIterator: public TProductIteratorBase<TEnumeratedSet, TValue> {
private:
TVector<ui64> FlatOffsets;
size_t OffsetIndex = 0;
public:
// pass count={any positive number} to iterate over random {count} elements
TRandomizedProductIterator(const TVector<TEnumeratedSet>& sets, ui32 count, bool allowRepeat = false)
: TProductIteratorBase<TEnumeratedSet, TValue>(sets) {
CB_ENSURE(count > 0, "Error: param count for TRandomizedProductIterator should be a positive number");
ui64 totalCount = this->TotalElementsCount;
if (count > totalCount && !allowRepeat) {
count = totalCount;
}
TVector<ui64> indexes;
if (static_cast<double>(count) / totalCount > 0.7 && !allowRepeat) {
indexes.resize(totalCount);
std::iota(indexes.begin(), indexes.end(), 1);
Shuffle(indexes.begin(), indexes.end());
indexes.resize(count);
} else {
TSet<ui64> choosenIndexes;
TRandom random;
while (indexes.size() != count) {
ui64 nextRandom = random.NextUniformL() % totalCount;
while (choosenIndexes.contains(nextRandom)) {
nextRandom = random.NextUniformL() % totalCount;
}
indexes.push_back(nextRandom);
if (!allowRepeat) {
choosenIndexes.insert(nextRandom);
}
}
}
Sort(indexes);
ui64 lastIndex = 0;
for (const auto& index : indexes) {
FlatOffsets.push_back(index - lastIndex);
lastIndex = index;
}
this->TotalElementsCount = count;
}
virtual bool Next(TConstArrayRef<TValue>* values) override {
if (this->IsIteratorReachedEnd()) {
return false;
}
ui64 offset = 1;
offset = FlatOffsets[OffsetIndex];
++OffsetIndex;
this->PassedElementsCount++;
*values = this->NextWithOffset(offset);
return true;
}
};
struct TGeneralQuatizationParamsInfo {
bool IsBordersCountInGrid = false;
bool IsBorderTypeInGrid = false;
bool IsNanModeInGrid = false;
TString BordersCountParamName = BorderCountParamAliaces[0];
TString BorderTypeParamName = BorderTypeParamAliaces[0];
TString NanModeParamName = NanModeParamAliaces[0];
};
struct TQuantizationParamsInfo {
int BinsCount = -1;
EBorderSelectionType BorderType;
ENanMode NanMode;
TGeneralQuatizationParamsInfo GeneralInfo;
};
struct TGridParamsInfo {
TQuantizationParamsInfo QuantizationParamsSet;
NCB::TQuantizedFeaturesInfoPtr QuantizedFeatureInfo;
NJson::TJsonValue OthersParamsSet;
TVector<TString> GridParamNames;
};
bool CheckIfRandomDisribution(const TString& value) {
return value.rfind("CustomRandomDistributionGenerator", 0) == 0;
}
NJson::TJsonValue GetRandomValueIfNeeded(
const NJson::TJsonValue& value,
const THashMap<TString, NCB::TCustomRandomDistributionGenerator>& randDistGen) {
if (value.GetType() == NJson::EJsonValueType::JSON_STRING) {
if (CheckIfRandomDisribution(value.GetString())) {
CB_ENSURE(
randDistGen.find(value.GetString()) != randDistGen.end(),
"Error: Reference to unknown random distribution generator"
);
const auto& rnd = randDistGen.at(value.GetString());
return NJson::TJsonValue(rnd.EvalFunc(rnd.CustomData));
}
}
return value;
}
void AssignOptionsToJson(
TConstArrayRef<TString> names,
TConstArrayRef<NJson::TJsonValue> values,
const THashMap<TString, NCB::TCustomRandomDistributionGenerator>& randDistGen,
NJson::TJsonValue* jsonValues) {
CB_ENSURE(names.size() == values.size(), "Error: names and values should have same size");
for (size_t i : xrange(names.size())) {
(*jsonValues)[names[i]] = GetRandomValueIfNeeded(values[i], randDistGen);
}
}
NCB::TTrainingDataProviders PrepareTrainTestSplit(
NCB::TTrainingDataProviderPtr srcData,
const TTrainTestSplitParams& trainTestSplitParams,
ui64 cpuUsedRamLimit,
NPar::TLocalExecutor* localExecutor) {
CB_ENSURE(
srcData->ObjectsData->GetOrder() != NCB::EObjectsOrder::Ordered,
"Params search for ordered objects data is not yet implemented"
);
NCB::TArraySubsetIndexing<ui32> trainIndices;
NCB::TArraySubsetIndexing<ui32> testIndices;
if (trainTestSplitParams.Stratified) {
NCB::TMaybeData<TConstArrayRef<float>> maybeTarget
= srcData->TargetData->GetOneDimensionalTarget();
CB_ENSURE(maybeTarget, "Cannot do stratified split: Target data is unavailable");
NCB::StratifiedTrainTestSplit(
*srcData->ObjectsGrouping,
*maybeTarget,
trainTestSplitParams.TrainPart,
&trainIndices,
&testIndices
);
} else {
TrainTestSplit(
*srcData->ObjectsGrouping,
trainTestSplitParams.TrainPart,
&trainIndices,
&testIndices
);
}
return NCB::CreateTrainTestSubsets<NCB::TTrainingDataProviders>(
srcData,
std::move(trainIndices),
std::move(testIndices),
cpuUsedRamLimit,
localExecutor
);
}
bool TryCheckParamType(
const TString& paramName,
const TSet<NJson::EJsonValueType>& allowedTypes,
const NJson::TJsonValue& gridJsonValues) {
if (!gridJsonValues.GetMap().contains(paramName)) {
return false;
}
const auto& jsonValues = gridJsonValues.GetMap().at(paramName);
for (const auto& value : jsonValues.GetArray()) {
const auto type = value.GetType();
if (allowedTypes.find(type) != allowedTypes.end()) {
continue;
}
if (type == NJson::EJsonValueType::JSON_STRING && CheckIfRandomDisribution(value.GetString())) {
continue;
}
ythrow TCatBoostException() << "Can't parse parameter \"" << paramName
<< "\" with value: " << value;
}
return true;
}
template <class T, typename Func>
void FindAndExtractParam(
const TVector<TString>& paramAliases,
const NCatboostOptions::TOption<T>& option,
const TSet<NJson::EJsonValueType>& allowedTypes,
const Func& typeCaster,
bool* isInGrid,
TString* exactParamName,
TDeque<NJson::TJsonValue>* values,
NJson::TJsonValue* gridJsonValues,
NJson::TJsonValue* modelJsonParams) {
for (const auto& paramName : paramAliases) {
*exactParamName = paramName;
*isInGrid = TryCheckParamType(
*exactParamName,
allowedTypes,
*gridJsonValues
);
if (*isInGrid) {
break;
}
}
if (*isInGrid) {
*values = (*gridJsonValues)[*exactParamName].GetArray();
gridJsonValues->EraseValue(*exactParamName);
modelJsonParams->EraseValue(*exactParamName);
} else {
values->push_back(
NJson::TJsonValue(
typeCaster(option.Get())
)
);
}
}
void FindAndExtractGridQuantizationParams(
const NCatboostOptions::TCatBoostOptions& catBoostOptions,
TDeque<NJson::TJsonValue>* borderMaxCounts,
bool* isBordersCountInGrid,
TString* borderCountsParamName,
TDeque<NJson::TJsonValue>* borderTypes,
bool* isBorderTypeInGrid,
TString* borderTypesParamName,
TDeque<NJson::TJsonValue>* nanModes,
bool* isNanModeInGrid,
TString* nanModesParamName,
NJson::TJsonValue* gridJsonValues,
NJson::TJsonValue* modelJsonParams) {
FindAndExtractParam(
BorderCountParamAliaces,
catBoostOptions.DataProcessingOptions->FloatFeaturesBinarization.Get().BorderCount,
{
NJson::EJsonValueType::JSON_INTEGER,
NJson::EJsonValueType::JSON_UINTEGER,
NJson::EJsonValueType::JSON_DOUBLE
},
[](ui32 value){ return value; },
isBordersCountInGrid,
borderCountsParamName,
borderMaxCounts,
gridJsonValues,
modelJsonParams
);
FindAndExtractParam(
BorderTypeParamAliaces,
catBoostOptions.DataProcessingOptions->FloatFeaturesBinarization.Get().BorderSelectionType,
{NJson::EJsonValueType::JSON_STRING},
[](EBorderSelectionType value){ return ToString(value); },
isBorderTypeInGrid,
borderTypesParamName,
borderTypes,
gridJsonValues,
modelJsonParams
);
FindAndExtractParam(
NanModeParamAliaces,
catBoostOptions.DataProcessingOptions->FloatFeaturesBinarization.Get().NanMode,
{NJson::EJsonValueType::JSON_STRING},
[](ENanMode value){ return ToString(value); },
isNanModeInGrid,
nanModesParamName,
nanModes,
gridJsonValues,
modelJsonParams
);
}
bool QuantizeDataIfNeeded(
bool allowWriteFiles,
const TString& tmpDir,
NCB::TFeaturesLayoutPtr featuresLayout,
NCB::TQuantizedFeaturesInfoPtr quantizedFeaturesInfo,
NCB::TDataProviderPtr data,
const TQuantizationParamsInfo& oldQuantizedParamsInfo,
const TQuantizationParamsInfo& newQuantizedParamsInfo,
TLabelConverter* labelConverter,
NPar::TLocalExecutor* localExecutor,
TRestorableFastRng64* rand,
NCatboostOptions::TCatBoostOptions* catBoostOptions,
NCB::TTrainingDataProviderPtr* result) {
if (oldQuantizedParamsInfo.BinsCount != newQuantizedParamsInfo.BinsCount ||
oldQuantizedParamsInfo.BorderType != newQuantizedParamsInfo.BorderType ||
oldQuantizedParamsInfo.NanMode != newQuantizedParamsInfo.NanMode)
{
NCatboostOptions::TBinarizationOptions commonFloatFeaturesBinarization(
newQuantizedParamsInfo.BorderType,
newQuantizedParamsInfo.BinsCount,
newQuantizedParamsInfo.NanMode
);
TVector<ui32> ignoredFeatureNums; // TODO(ilikepugs): MLTOOLS-3838
TMaybe<float> targetBorder = catBoostOptions->DataProcessingOptions->TargetBorder;
quantizedFeaturesInfo = MakeIntrusive<NCB::TQuantizedFeaturesInfo>(
*(featuresLayout.Get()),
MakeConstArrayRef(ignoredFeatureNums),
commonFloatFeaturesBinarization,
/*perFloatFeatureQuantization*/TMap<ui32, NCatboostOptions::TBinarizationOptions>(),
/*floatFeaturesAllowNansInTestOnly*/true
);
// Quantizing training data
*result = GetTrainingData(
data,
/*isLearnData*/ true,
/*datasetName*/ TStringBuf(),
/*bordersFile*/ Nothing(), // Already at quantizedFeaturesInfo
/*unloadCatFeaturePerfectHashFromRam*/ allowWriteFiles,
/*ensureConsecutiveLearnFeaturesDataForCpu*/ true,
tmpDir,
quantizedFeaturesInfo,
catBoostOptions,
labelConverter,
&targetBorder,
localExecutor,
rand
);
return true;
}
return false;
}
bool QuantizeAndSplitDataIfNeeded(
bool allowWriteFiles,
const TString& tmpDir,
const TTrainTestSplitParams& trainTestSplitParams,
ui64 cpuUsedRamLimit,
NCB::TFeaturesLayoutPtr featuresLayout,
NCB::TQuantizedFeaturesInfoPtr quantizedFeaturesInfo,
NCB::TDataProviderPtr data,
const TQuantizationParamsInfo& oldQuantizedParamsInfo,
const TQuantizationParamsInfo& newQuantizedParamsInfo,
TLabelConverter* labelConverter,
NPar::TLocalExecutor* localExecutor,
TRestorableFastRng64* rand,
NCatboostOptions::TCatBoostOptions* catBoostOptions,
NCB::TTrainingDataProviders* result) {
NCB::TTrainingDataProviderPtr quantizedData;
bool isNeedSplit = QuantizeDataIfNeeded(
allowWriteFiles,
tmpDir,
featuresLayout,
quantizedFeaturesInfo,
data,
oldQuantizedParamsInfo,
newQuantizedParamsInfo,
labelConverter,
localExecutor,
rand,
catBoostOptions,
&quantizedData
);
if (isNeedSplit) {
// Train-test split
*result = PrepareTrainTestSplit(
quantizedData,
trainTestSplitParams,
cpuUsedRamLimit,
localExecutor
);
return true;
}
return false;
}
void ParseGridParams(
const NCatboostOptions::TCatBoostOptions& catBoostOptions,
NJson::TJsonValue* jsonGrid,
NJson::TJsonValue* modelJsonParams,
TVector<TString>* paramNames,
TVector<TDeque<NJson::TJsonValue>>* paramPossibleValues,
TGeneralQuatizationParamsInfo* generalQuantizeParamsInfo) {
paramPossibleValues->resize(3);
FindAndExtractGridQuantizationParams(
catBoostOptions,
&(*paramPossibleValues)[0],
&generalQuantizeParamsInfo->IsBordersCountInGrid,
&generalQuantizeParamsInfo->BordersCountParamName,
&(*paramPossibleValues)[1],
&generalQuantizeParamsInfo->IsBorderTypeInGrid,
&generalQuantizeParamsInfo->BorderTypeParamName,
&(*paramPossibleValues)[2],
&generalQuantizeParamsInfo->IsNanModeInGrid,
&generalQuantizeParamsInfo->NanModeParamName,
jsonGrid,
modelJsonParams
);
for (const auto& set : jsonGrid->GetMap()) {
paramNames->push_back(set.first);
paramPossibleValues->resize(paramPossibleValues->size() + 1);
CB_ENSURE(set.second.GetArray().size() > 0, "Error: an empty set of values for parameter " + paramNames->back());
for (auto& value : set.second.GetArray()) {
(*paramPossibleValues)[paramPossibleValues->size() - 1].push_back(value);
}
}
}
void SetGridParamsToBestOptionValues(
const TGridParamsInfo & gridParams,
NCB::TBestOptionValuesWithCvResult* namedOptionsCollection) {
namedOptionsCollection->SetOptionsFromJson(gridParams.OthersParamsSet.GetMap(), gridParams.GridParamNames);
// Adding quantization params if needed
if (gridParams.QuantizationParamsSet.GeneralInfo.IsBordersCountInGrid) {
const TString& paramName = gridParams.QuantizationParamsSet.GeneralInfo.BordersCountParamName;
namedOptionsCollection->IntOptions[paramName] = gridParams.QuantizationParamsSet.BinsCount;
}
if (gridParams.QuantizationParamsSet.GeneralInfo.IsBorderTypeInGrid) {
const TString& paramName = gridParams.QuantizationParamsSet.GeneralInfo.BorderTypeParamName;
namedOptionsCollection->StringOptions[paramName] = ToString(gridParams.QuantizationParamsSet.BorderType);
}
if (gridParams.QuantizationParamsSet.GeneralInfo.IsNanModeInGrid) {
const TString& paramName = gridParams.QuantizationParamsSet.GeneralInfo.NanModeParamName;
namedOptionsCollection->StringOptions[paramName] = ToString(gridParams.QuantizationParamsSet.NanMode);
}
}
int GetSignForMetricMinimization(const THolder<IMetric>& metric) {
EMetricBestValue metricValueType;
metric->GetBestValue(&metricValueType, nullptr); // Choosing best params only by first metric
int metricSign;
if (metricValueType == EMetricBestValue::Min) {
metricSign = 1;
} else if (metricValueType == EMetricBestValue::Max) {
metricSign = -1;
} else {
CB_ENSURE(false, "Error: metric for grid search must be minimized or maximized");
}
return metricSign;
}
bool SetBestParamsAndUpdateMetricValueIfNeeded(
double metricValue,
const TVector<THolder<IMetric>>& metrics,
const TQuantizationParamsInfo& quantizationParamsSet,
const NJson::TJsonValue& modelParamsToBeTried,
const TVector<TString>& paramNames,
NCB::TQuantizedFeaturesInfoPtr quantizedFeaturesInfo,
TGridParamsInfo* bestGridParams,
double* bestParamsSetMetricValue) {
int metricSign = GetSignForMetricMinimization(metrics[0]);
if (metricSign * metricValue < *bestParamsSetMetricValue * metricSign) {
*bestParamsSetMetricValue = metricValue;
bestGridParams->QuantizationParamsSet = quantizationParamsSet;
bestGridParams->OthersParamsSet = modelParamsToBeTried;
bestGridParams->QuantizedFeatureInfo = quantizedFeaturesInfo;
bestGridParams->GridParamNames = paramNames;
return true;
}
return false;
}
static TString GetNamesPrefix(ui32 foldIdx) {
return "fold_" + ToString(foldIdx) + "_";
}
static void InitializeFilesLoggers(
const TVector<THolder<IMetric>>& metrics,
const TOutputFiles& outputFiles,
const int iterationCount,
const ELaunchMode launchMode,
const int foldCountOrTestSize,
const TString& parametersToken,
TLogger* logger
) {
TVector<TString> learnSetNames;
TVector<TString> testSetNames;
switch (launchMode) {
case ELaunchMode::CV: {
for (auto foldIdx : xrange(foldCountOrTestSize)) {
learnSetNames.push_back("fold_" + ToString(foldIdx) + "_learn");
testSetNames.push_back("fold_" + ToString(foldIdx) + "_test");
}
break;
}
case ELaunchMode::Train: {
const auto& learnToken = GetTrainModelLearnToken();
const auto& testTokens = GetTrainModelTestTokens(foldCountOrTestSize);
learnSetNames = { outputFiles.NamesPrefix + learnToken };
for (int testIdx = 0; testIdx < testTokens.ysize(); ++testIdx) {
testSetNames.push_back({ outputFiles.NamesPrefix + testTokens[testIdx] });
}
break;
}
default: CB_ENSURE(false, "unexpected launchMode" << launchMode);
}
AddFileLoggers(
false,
outputFiles.LearnErrorLogFile,
outputFiles.TestErrorLogFile,
outputFiles.TimeLeftLogFile,
outputFiles.JsonLogFile,
outputFiles.ProfileLogFile,
outputFiles.TrainDir,
GetJsonMeta(
iterationCount,
outputFiles.ExperimentName,
GetConstPointers(metrics),
learnSetNames,
testSetNames,
parametersToken,
launchMode),
/*metric period*/ 1,
logger
);
}
static void LogTrainTest(
const TString& lossDescription,
TOneInterationLogger& oneIterLogger,
const TMaybe<double> bestLearnResult,
const double bestTestResult,
const TString& learnToken,
const TString& testToken,
bool isMainMetric) {
if (bestLearnResult.Defined()) {
oneIterLogger.OutputMetric(
learnToken,
TMetricEvalResult(
lossDescription,
*bestLearnResult,
isMainMetric
)
);
}
oneIterLogger.OutputMetric(
testToken,
TMetricEvalResult(
lossDescription,
bestTestResult,
isMainMetric
)
);
}
static void LogParameters(
const TVector<TString>& paramNames,
TConstArrayRef<NJson::TJsonValue> paramsSet,
const TString& parametersToken,
const TGeneralQuatizationParamsInfo& generalQuantizeParamsInfo,
TOneInterationLogger& oneIterLogger) {
NJson::TJsonValue jsonParams;
// paramsSet: {border_count, feature_border_type, nan_mode, [others]}
if (generalQuantizeParamsInfo.IsBordersCountInGrid) {
jsonParams.InsertValue(generalQuantizeParamsInfo.BordersCountParamName, paramsSet[0]);
}
if (generalQuantizeParamsInfo.IsBorderTypeInGrid) {
jsonParams.InsertValue(generalQuantizeParamsInfo.BorderTypeParamName, paramsSet[1]);
}
if (generalQuantizeParamsInfo.IsNanModeInGrid) {
jsonParams.InsertValue(generalQuantizeParamsInfo.NanModeParamName, paramsSet[2]);
}
for (size_t idx = IndexOfFirstTrainingParameter; idx < paramsSet.size(); ++idx) {
const auto key = paramNames[idx - IndexOfFirstTrainingParameter];
jsonParams.InsertValue(key, paramsSet[idx]);
}
oneIterLogger.OutputParameters(parametersToken, jsonParams);
}
bool ParseJsonParams(
const NCB::TDataMetaInfo& metaInfo,
const NJson::TJsonValue& modelParamsToBeTried,
NCatboostOptions::TCatBoostOptions *catBoostOptions,
NCatboostOptions::TOutputFilesOptions *outputFileOptions) {
try {
NJson::TJsonValue jsonParams;
NJson::TJsonValue outputJsonParams;
NCatboostOptions::PlainJsonToOptions(modelParamsToBeTried, &jsonParams, &outputJsonParams);
ConvertParamsToCanonicalFormat(metaInfo, &jsonParams);
*catBoostOptions = NCatboostOptions::LoadOptions(jsonParams);
outputFileOptions->Load(outputJsonParams);
return true;
} catch (const TCatBoostException&) {
return false;
}
}
double TuneHyperparamsCV(
const TVector<TString>& paramNames,
const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,
const TMaybe<TCustomMetricDescriptor>& evalMetricDescriptor,
const TCrossValidationParams& cvParams,
const TGeneralQuatizationParamsInfo& generalQuantizeParamsInfo,
ui64 cpuUsedRamLimit,
NCB::TDataProviderPtr data,
TProductIteratorBase<TDeque<NJson::TJsonValue>, NJson::TJsonValue>* gridIterator,
NJson::TJsonValue* modelParamsToBeTried,
TGridParamsInfo* bestGridParams,
TVector<TCVResult>* bestCvResult,
NPar::TLocalExecutor* localExecutor,
int verbose,
const THashMap<TString, NCB::TCustomRandomDistributionGenerator>& randDistGenerators = {}) {
TRestorableFastRng64 rand(cvParams.PartitionRandSeed);
if (cvParams.Shuffle) {
auto objectsGroupingSubset = NCB::Shuffle(data->ObjectsGrouping, 1, &rand);
data = data->GetSubset(objectsGroupingSubset, cpuUsedRamLimit, localExecutor);
}
TSetLogging inThisScope(ELoggingLevel::Debug);
TLogger logger;
const auto parametersToken = GetParametersToken();
TString searchToken = "loss";
AddConsoleLogger(
searchToken,
{},
/*hasTrain=*/true,
verbose,
gridIterator->GetTotalElementsCount(),
&logger
);
double bestParamsSetMetricValue = 0;
// Other parameters
NCB::TTrainingDataProviderPtr quantizedData;
TQuantizationParamsInfo lastQuantizationParamsSet;
TLabelConverter labelConverter;
int iterationIdx = 0;
int bestIterationIdx = 0;
TProfileInfo profile(gridIterator->GetTotalElementsCount());
TConstArrayRef<NJson::TJsonValue> paramsSet;
while (gridIterator->Next(¶msSet)) {
profile.StartIterationBlock();
// paramsSet: {border_count, feature_border_type, nan_mode, [others]}
TQuantizationParamsInfo quantizationParamsSet;
quantizationParamsSet.BinsCount = GetRandomValueIfNeeded(paramsSet[0], randDistGenerators).GetInteger();
quantizationParamsSet.BorderType = FromString<EBorderSelectionType>(paramsSet[1].GetString());
quantizationParamsSet.NanMode = FromString<ENanMode>(paramsSet[2].GetString());
AssignOptionsToJson(
TConstArrayRef<TString>(paramNames),
TConstArrayRef<NJson::TJsonValue>(
paramsSet.begin() + IndexOfFirstTrainingParameter,
paramsSet.end()
), // Ignoring quantization params
randDistGenerators,
modelParamsToBeTried
);
NCatboostOptions::TCatBoostOptions catBoostOptions(ETaskType::CPU);
NCatboostOptions::TOutputFilesOptions outputFileOptions;
bool areParamsValid = ParseJsonParams(
data.Get()->MetaInfo,
*modelParamsToBeTried,
&catBoostOptions,
&outputFileOptions
);
if (!areParamsValid) {
continue;
}
TString tmpDir;
if (outputFileOptions.AllowWriteFiles()) {
NCB::NPrivate::CreateTrainDirWithTmpDirIfNotExist(outputFileOptions.GetTrainDir(), &tmpDir);
}
InitializeEvalMetricIfNotSet(catBoostOptions.MetricOptions->ObjectiveMetric, &catBoostOptions.MetricOptions->EvalMetric);
NCB::TFeaturesLayoutPtr featuresLayout = data->MetaInfo.FeaturesLayout;
NCB::TQuantizedFeaturesInfoPtr quantizedFeaturesInfo;
TMetricsAndTimeLeftHistory metricsAndTimeHistory;
TVector<TCVResult> cvResult;
{
TSetLogging inThisScope(catBoostOptions.LoggingLevel);
QuantizeDataIfNeeded(
outputFileOptions.AllowWriteFiles(),
tmpDir,
featuresLayout,
quantizedFeaturesInfo,
data,
lastQuantizationParamsSet,
quantizationParamsSet,
&labelConverter,
localExecutor,
&rand,
&catBoostOptions,
&quantizedData
);
lastQuantizationParamsSet = quantizationParamsSet;
CrossValidate(
*modelParamsToBeTried,
objectiveDescriptor,
evalMetricDescriptor,
labelConverter,
quantizedData,
cvParams,
localExecutor,
&cvResult);
}
ui32 approxDimension = NCB::GetApproxDimension(catBoostOptions, labelConverter, data->RawTargetData.GetTargetDimension());
const TVector<THolder<IMetric>> metrics = CreateMetrics(
catBoostOptions.MetricOptions,
evalMetricDescriptor,
approxDimension,
quantizedData->MetaInfo.HasWeights
);
double bestMetricValue = cvResult[0].AverageTest.back(); //[testId][lossDescription]
if (iterationIdx == 0) {
// We guarantee to update the parameters on the first iteration
bestParamsSetMetricValue = cvResult[0].AverageTest.back() + GetSignForMetricMinimization(metrics[0]);
if (outputFileOptions.AllowWriteFiles()) {
// Initialize Files Loggers
TString namesPrefix = "fold_0_";
TOutputFiles outputFiles(outputFileOptions, namesPrefix);
InitializeFilesLoggers(
metrics,
outputFiles,
gridIterator->GetTotalElementsCount(),
ELaunchMode::CV,
cvParams.FoldCount,
parametersToken,
&logger
);
}
}
bool isUpdateBest = SetBestParamsAndUpdateMetricValueIfNeeded(
bestMetricValue,
metrics,
quantizationParamsSet,
*modelParamsToBeTried,
paramNames,
quantizedFeaturesInfo,
bestGridParams,
&bestParamsSetMetricValue);
if (isUpdateBest) {
bestIterationIdx = iterationIdx;
*bestCvResult = cvResult;
}
const TString& lossDescription = metrics[0]->GetDescription();
TOneInterationLogger oneIterLogger(logger);
oneIterLogger.OutputMetric(
searchToken,
TMetricEvalResult(
lossDescription,
bestMetricValue,
bestParamsSetMetricValue,
bestIterationIdx,
true
)
);
if (outputFileOptions.AllowWriteFiles()) {
//log metrics
const auto& skipMetricOnTrain = GetSkipMetricOnTrain(metrics);
for (auto foldIdx : xrange((size_t)cvParams.FoldCount)) {
for (auto metricIdx : xrange(metrics.size())) {
LogTrainTest(
metrics[metricIdx]->GetDescription(),
oneIterLogger,
skipMetricOnTrain[metricIdx] ? Nothing() :
MakeMaybe<double>(cvResult[metricIdx].LastTrainEvalMetric[foldIdx]),
cvResult[metricIdx].LastTestEvalMetric[foldIdx],
GetNamesPrefix(foldIdx) + "learn",
GetNamesPrefix(foldIdx) + "test",
metricIdx == 0
);
}
}
//log parameters
LogParameters(
paramNames,
paramsSet,
parametersToken,
generalQuantizeParamsInfo,
oneIterLogger
);
}
profile.FinishIterationBlock(1);
oneIterLogger.OutputProfile(profile.GetProfileResults());
iterationIdx++;
}
return bestParamsSetMetricValue;
}
double TuneHyperparamsTrainTest(
const TVector<TString>& paramNames,
const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,
const TMaybe<TCustomMetricDescriptor>& evalMetricDescriptor,
const TTrainTestSplitParams& trainTestSplitParams,
const TGeneralQuatizationParamsInfo& generalQuantizeParamsInfo,
ui64 cpuUsedRamLimit,
NCB::TDataProviderPtr data,
TProductIteratorBase<TDeque<NJson::TJsonValue>, NJson::TJsonValue>* gridIterator,
NJson::TJsonValue* modelParamsToBeTried,
TGridParamsInfo * bestGridParams,
TMetricsAndTimeLeftHistory* trainTestResult,
NPar::TLocalExecutor* localExecutor,
int verbose,
const THashMap<TString, NCB::TCustomRandomDistributionGenerator>& randDistGenerators = {}) {
TRestorableFastRng64 rand(trainTestSplitParams.PartitionRandSeed);
if (trainTestSplitParams.Shuffle) {
auto objectsGroupingSubset = NCB::Shuffle(data->ObjectsGrouping, 1, &rand);
data = data->GetSubset(objectsGroupingSubset, cpuUsedRamLimit, localExecutor);
}
TSetLogging inThisScope(ELoggingLevel::Verbose);
TLogger logger;
TString searchToken = "loss";
const auto parametersToken = GetParametersToken();
AddConsoleLogger(
searchToken,
{},
/*hasTrain=*/true,
verbose,
gridIterator->GetTotalElementsCount(),
&logger
);
double bestParamsSetMetricValue = 0;
// Other parameters
NCB::TTrainingDataProviders trainTestData;
TQuantizationParamsInfo lastQuantizationParamsSet;
TLabelConverter labelConverter;
int iterationIdx = 0;
int bestIterationIdx = 0;
TProfileInfo profile(gridIterator->GetTotalElementsCount());
TConstArrayRef<NJson::TJsonValue> paramsSet;
while (gridIterator->Next(¶msSet)) {
profile.StartIterationBlock();
// paramsSet: {border_count, feature_border_type, nan_mode, [others]}
TQuantizationParamsInfo quantizationParamsSet;
quantizationParamsSet.BinsCount = GetRandomValueIfNeeded(paramsSet[0], randDistGenerators).GetInteger();
quantizationParamsSet.BorderType = FromString<EBorderSelectionType>(paramsSet[1].GetString());
quantizationParamsSet.NanMode = FromString<ENanMode>(paramsSet[2].GetString());
AssignOptionsToJson(
TConstArrayRef<TString>(paramNames),
TConstArrayRef<NJson::TJsonValue>(
paramsSet.begin() + IndexOfFirstTrainingParameter,
paramsSet.end()
), // Ignoring quantization params
randDistGenerators,
modelParamsToBeTried
);
NCatboostOptions::TCatBoostOptions catBoostOptions(ETaskType::CPU);
NCatboostOptions::TOutputFilesOptions outputFileOptions;
bool areParamsValid = ParseJsonParams(
data.Get()->MetaInfo,
*modelParamsToBeTried,
&catBoostOptions,
&outputFileOptions
);
if (!areParamsValid) {
continue;
}
static const bool allowWriteFiles = outputFileOptions.AllowWriteFiles();
TString tmpDir;
if (allowWriteFiles) {
NCB::NPrivate::CreateTrainDirWithTmpDirIfNotExist(outputFileOptions.GetTrainDir(), &tmpDir);
}
InitializeEvalMetricIfNotSet(catBoostOptions.MetricOptions->ObjectiveMetric, &catBoostOptions.MetricOptions->EvalMetric);
UpdateSampleRateOption(data->GetObjectCount(), &catBoostOptions);
NCB::TFeaturesLayoutPtr featuresLayout = data->MetaInfo.FeaturesLayout;
NCB::TQuantizedFeaturesInfoPtr quantizedFeaturesInfo;
TMetricsAndTimeLeftHistory metricsAndTimeHistory;
{
TSetLogging inThisScope(catBoostOptions.LoggingLevel);
QuantizeAndSplitDataIfNeeded(
allowWriteFiles,
tmpDir,
trainTestSplitParams,
cpuUsedRamLimit,
featuresLayout,
quantizedFeaturesInfo,
data,
lastQuantizationParamsSet,
quantizationParamsSet,
&labelConverter,
localExecutor,
&rand,
&catBoostOptions,
&trainTestData
);
lastQuantizationParamsSet = quantizationParamsSet;
THolder<IModelTrainer> modelTrainerHolder = TTrainerFactory::Construct(catBoostOptions.GetTaskType());
TEvalResult evalRes;
TTrainModelInternalOptions internalOptions;
internalOptions.CalcMetricsOnly = true;
internalOptions.ForceCalcEvalMetricOnEveryIteration = false;
internalOptions.OffsetMetricPeriodByInitModelSize = true;
outputFileOptions.SetAllowWriteFiles(false);
const auto defaultTrainingCallbacks = MakeHolder<ITrainingCallbacks>();
// Training model
modelTrainerHolder->TrainModel(
internalOptions,
catBoostOptions,
outputFileOptions,
objectiveDescriptor,
evalMetricDescriptor,
trainTestData,
labelConverter,
defaultTrainingCallbacks.Get(), // TODO(ilikepugs): MLTOOLS-3540
/*initModel*/ Nothing(),
/*initLearnProgress*/ nullptr,
/*initModelApplyCompatiblePools*/ NCB::TDataProviders(),
localExecutor,
&rand,
/*dstModel*/ nullptr,
/*evalResultPtrs*/ {&evalRes},
&metricsAndTimeHistory,
/*dstLearnProgress*/nullptr
);
}
ui32 approxDimension = NCB::GetApproxDimension(catBoostOptions, labelConverter, data->RawTargetData.GetTargetDimension());
const TVector<THolder<IMetric>> metrics = CreateMetrics(
catBoostOptions.MetricOptions,
evalMetricDescriptor,
approxDimension,
data->MetaInfo.HasWeights
);
const TString& lossDescription = metrics[0]->GetDescription();
double bestMetricValue = metricsAndTimeHistory.TestBestError[0][lossDescription]; //[testId][lossDescription]
if (iterationIdx == 0) {
// We guarantee to update the parameters on the first iteration
bestParamsSetMetricValue = bestMetricValue + GetSignForMetricMinimization(metrics[0]);
outputFileOptions.SetAllowWriteFiles(allowWriteFiles);
if (allowWriteFiles) {
// Initialize Files Loggers
TOutputFiles outputFiles(outputFileOptions, "");
InitializeFilesLoggers(
metrics,
outputFiles,
gridIterator->GetTotalElementsCount(),
ELaunchMode::Train,
trainTestData.Test.ysize(),
parametersToken,
&logger
);
}
(*trainTestResult) = metricsAndTimeHistory;
}
bool isUpdateBest = SetBestParamsAndUpdateMetricValueIfNeeded(
bestMetricValue,
metrics,
quantizationParamsSet,
*modelParamsToBeTried,
paramNames,
quantizedFeaturesInfo,
bestGridParams,
&bestParamsSetMetricValue);
if (isUpdateBest) {
bestIterationIdx = iterationIdx;
(*trainTestResult) = metricsAndTimeHistory;
}
TOneInterationLogger oneIterLogger(logger);
oneIterLogger.OutputMetric(
searchToken,
TMetricEvalResult(
lossDescription,
bestMetricValue,
bestParamsSetMetricValue,
bestIterationIdx,
true
)
);
if (allowWriteFiles) {
//log metrics
const auto& skipMetricOnTrain = GetSkipMetricOnTrain(metrics);
auto& learnErrors = metricsAndTimeHistory.LearnBestError;
auto& testErrors = metricsAndTimeHistory.TestBestError[0];
for (auto metricIdx : xrange(metrics.size())) {
const auto& lossDescription = metrics[metricIdx]->GetDescription();
LogTrainTest(
lossDescription,
oneIterLogger,
skipMetricOnTrain[metricIdx] ? Nothing() :
MakeMaybe<double>(learnErrors.at(lossDescription)),
testErrors.at(lossDescription),
"learn",
"test",
metricIdx == 0
);
}
//log parameters
LogParameters(
paramNames,
paramsSet,
parametersToken,
generalQuantizeParamsInfo,
oneIterLogger
);
}
profile.FinishIterationBlock(1);
oneIterLogger.OutputProfile(profile.GetProfileResults());
iterationIdx++;
}
return bestParamsSetMetricValue;
}
} // anonymous namespace
namespace NCB {
void TBestOptionValuesWithCvResult::SetOptionsFromJson(
const THashMap<TString, NJson::TJsonValue>& options,
const TVector<TString>& optionsNames) {
BoolOptions.clear();
IntOptions.clear();
UIntOptions.clear();
DoubleOptions.clear();
StringOptions.clear();
ListOfDoublesOptions.clear();
for (const auto& optionName : optionsNames) {
const auto& option = options.at(optionName);
NJson::EJsonValueType type = option.GetType();
switch(type) {
case NJson::EJsonValueType::JSON_BOOLEAN: {
BoolOptions[optionName] = option.GetBoolean();
break;
}
case NJson::EJsonValueType::JSON_INTEGER: {
IntOptions[optionName] = option.GetInteger();
break;
}
case NJson::EJsonValueType::JSON_UINTEGER: {
UIntOptions[optionName] = option.GetUInteger();
break;
}
case NJson::EJsonValueType::JSON_DOUBLE: {
DoubleOptions[optionName] = option.GetDouble();
break;
}
case NJson::EJsonValueType::JSON_STRING: {
StringOptions[optionName] = option.GetString();
break;
}
case NJson::EJsonValueType::JSON_ARRAY: {
for (const auto& listElement : option.GetArray()) {
ListOfDoublesOptions[optionName].push_back(listElement.GetDouble());
}
break;
}
default: {
CB_ENSURE(false, "Error: option value should be bool, int, ui32, double, string or list of doubles");
}
}
}
}
void GridSearch(
const NJson::TJsonValue& gridJsonValues,
const NJson::TJsonValue& modelJsonParams,
const TTrainTestSplitParams& trainTestSplitParams,
const TCrossValidationParams& cvParams,
const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,
const TMaybe<TCustomMetricDescriptor>& evalMetricDescriptor,
TDataProviderPtr data,
TBestOptionValuesWithCvResult* bestOptionValuesWithCvResult,
TMetricsAndTimeLeftHistory* trainTestResult,
bool isSearchUsingTrainTestSplit,
bool returnCvStat,
int verbose) {
// CatBoost options
NJson::TJsonValue jsonParams;
NJson::TJsonValue outputJsonParams;
NCatboostOptions::PlainJsonToOptions(modelJsonParams, &jsonParams, &outputJsonParams);
ConvertParamsToCanonicalFormat(data.Get()->MetaInfo, &jsonParams);
NCatboostOptions::TCatBoostOptions catBoostOptions(NCatboostOptions::LoadOptions(jsonParams));
NCatboostOptions::TOutputFilesOptions outputFileOptions;
outputFileOptions.Load(outputJsonParams);
CB_ENSURE(!outputJsonParams["save_snapshot"].GetBoolean(), "Snapshots are not yet supported for GridSearchCV");
InitializeEvalMetricIfNotSet(catBoostOptions.MetricOptions->ObjectiveMetric, &catBoostOptions.MetricOptions->EvalMetric);
NPar::TLocalExecutor localExecutor;
localExecutor.RunAdditionalThreads(catBoostOptions.SystemOptions->NumThreads.Get() - 1);
TGridParamsInfo bestGridParams;
TDeque<NJson::TJsonValue> paramGrids;
if (gridJsonValues.GetType() == NJson::EJsonValueType::JSON_MAP) {
paramGrids.push_back(gridJsonValues);
} else {
paramGrids = gridJsonValues.GetArray();
}
double bestParamsSetMetricValue = Max<double>();
TVector<TCVResult> bestCvResult;
for (auto gridEnumerator : xrange(paramGrids.size())) {
auto grid = paramGrids[gridEnumerator];
// Preparing parameters for cartesian product
TVector<TDeque<NJson::TJsonValue>> paramPossibleValues; // {border_count, feature_border_type, nan_mode, ...}
TGeneralQuatizationParamsInfo generalQuantizeParamsInfo;
TQuantizationParamsInfo quantizationParamsSet;
TVector<TString> paramNames;
NJson::TJsonValue modelParamsToBeTried(modelJsonParams);
TGridParamsInfo gridParams;
ParseGridParams(
catBoostOptions,
&grid,
&modelParamsToBeTried,
¶mNames,
¶mPossibleValues,
&generalQuantizeParamsInfo
);
TCartesianProductIterator<TDeque<NJson::TJsonValue>, NJson::TJsonValue> gridIterator(paramPossibleValues);
const ui64 cpuUsedRamLimit
= ParseMemorySizeDescription(catBoostOptions.SystemOptions->CpuUsedRamLimit.Get());
double metricValue;
if (verbose && paramGrids.size() > 1) {
TSetLogging inThisScope(ELoggingLevel::Verbose);
CATBOOST_NOTICE_LOG << "Grid #" << gridEnumerator << Endl;
}
if (isSearchUsingTrainTestSplit) {
metricValue = TuneHyperparamsTrainTest(
paramNames,
objectiveDescriptor,
evalMetricDescriptor,
trainTestSplitParams,
generalQuantizeParamsInfo,
cpuUsedRamLimit,
data,
&gridIterator,
&modelParamsToBeTried,
&gridParams,
trainTestResult,
&localExecutor,
verbose
);
} else {
metricValue = TuneHyperparamsCV(
paramNames,
objectiveDescriptor,
evalMetricDescriptor,
cvParams,
generalQuantizeParamsInfo,
cpuUsedRamLimit,
data,
&gridIterator,
&modelParamsToBeTried,
&gridParams,
&bestCvResult,
&localExecutor,
verbose
);
}
if (metricValue < bestParamsSetMetricValue) {
bestGridParams = gridParams;
bestGridParams.QuantizationParamsSet.GeneralInfo = generalQuantizeParamsInfo;
SetGridParamsToBestOptionValues(bestGridParams, bestOptionValuesWithCvResult);
}
}
if (returnCvStat || isSearchUsingTrainTestSplit) {
if (isSearchUsingTrainTestSplit) {
if (verbose) {
TSetLogging inThisScope(ELoggingLevel::Verbose);
CATBOOST_NOTICE_LOG << "Estimating final quality...\n";
}
CrossValidate(
bestGridParams.OthersParamsSet,
bestGridParams.QuantizedFeatureInfo,
objectiveDescriptor,
evalMetricDescriptor,
data,
cvParams,
&(bestOptionValuesWithCvResult->CvResult)
);
} else {
bestOptionValuesWithCvResult->CvResult = bestCvResult;
}
}
}
void RandomizedSearch(
ui32 numberOfTries,
const THashMap<TString, TCustomRandomDistributionGenerator>& randDistGenerators,
const NJson::TJsonValue& gridJsonValues,
const NJson::TJsonValue& modelJsonParams,
const TTrainTestSplitParams& trainTestSplitParams,
const TCrossValidationParams& cvParams,
const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,
const TMaybe<TCustomMetricDescriptor>& evalMetricDescriptor,
TDataProviderPtr data,
TBestOptionValuesWithCvResult* bestOptionValuesWithCvResult,
TMetricsAndTimeLeftHistory* trainTestResult,
bool isSearchUsingTrainTestSplit,
bool returnCvStat,
int verbose) {
// CatBoost options
NJson::TJsonValue jsonParams;
NJson::TJsonValue outputJsonParams;
NCatboostOptions::PlainJsonToOptions(modelJsonParams, &jsonParams, &outputJsonParams);
ConvertParamsToCanonicalFormat(data.Get()->MetaInfo, &jsonParams);
NCatboostOptions::TCatBoostOptions catBoostOptions(NCatboostOptions::LoadOptions(jsonParams));
NCatboostOptions::TOutputFilesOptions outputFileOptions;
outputFileOptions.Load(outputJsonParams);
CB_ENSURE(!outputJsonParams["save_snapshot"].GetBoolean(), "Snapshots are not yet supported for RandomizedSearchCV");
InitializeEvalMetricIfNotSet(catBoostOptions.MetricOptions->ObjectiveMetric, &catBoostOptions.MetricOptions->EvalMetric);
NPar::TLocalExecutor localExecutor;
localExecutor.RunAdditionalThreads(catBoostOptions.SystemOptions->NumThreads.Get() - 1);
NJson::TJsonValue paramGrid;
if (gridJsonValues.GetType() == NJson::EJsonValueType::JSON_MAP) {
paramGrid = gridJsonValues;
} else {
paramGrid = gridJsonValues.GetArray()[0];
}
// Preparing parameters for cartesian product
TVector<TDeque<NJson::TJsonValue>> paramPossibleValues; // {border_count, feature_border_type, nan_mode, ...}
TGeneralQuatizationParamsInfo generalQuantizeParamsInfo;
TQuantizationParamsInfo quantizationParamsSet;
TVector<TString> paramNames;
NJson::TJsonValue modelParamsToBeTried(modelJsonParams);
ParseGridParams(
catBoostOptions,
¶mGrid,
&modelParamsToBeTried,
¶mNames,
¶mPossibleValues,
&generalQuantizeParamsInfo
);
TRandomizedProductIterator<TDeque<NJson::TJsonValue>, NJson::TJsonValue> gridIterator(
paramPossibleValues,
numberOfTries,
randDistGenerators.size() > 0
);
const ui64 cpuUsedRamLimit
= ParseMemorySizeDescription(catBoostOptions.SystemOptions->CpuUsedRamLimit.Get());
TGridParamsInfo bestGridParams;
TVector<TCVResult> cvResult;
if (isSearchUsingTrainTestSplit) {
TuneHyperparamsTrainTest(
paramNames,
objectiveDescriptor,
evalMetricDescriptor,
trainTestSplitParams,
generalQuantizeParamsInfo,
cpuUsedRamLimit,
data,
&gridIterator,
&modelParamsToBeTried,
&bestGridParams,
trainTestResult,
&localExecutor,
verbose,
randDistGenerators
);
} else {
TuneHyperparamsCV(
paramNames,
objectiveDescriptor,
evalMetricDescriptor,
cvParams,
generalQuantizeParamsInfo,
cpuUsedRamLimit,
data,
&gridIterator,
&modelParamsToBeTried,
&bestGridParams,
&cvResult,
&localExecutor,
verbose,
randDistGenerators
);
}
bestGridParams.QuantizationParamsSet.GeneralInfo = generalQuantizeParamsInfo;
SetGridParamsToBestOptionValues(bestGridParams, bestOptionValuesWithCvResult);
if (returnCvStat || isSearchUsingTrainTestSplit) {
if (isSearchUsingTrainTestSplit) {
if (verbose) {
TSetLogging inThisScope(ELoggingLevel::Verbose);
CATBOOST_NOTICE_LOG << "Estimating final quality...\n";
}
CrossValidate(
bestGridParams.OthersParamsSet,
bestGridParams.QuantizedFeatureInfo,
objectiveDescriptor,
evalMetricDescriptor,
data,
cvParams,
&(bestOptionValuesWithCvResult->CvResult)
);
} else {
bestOptionValuesWithCvResult->CvResult = cvResult;
}
}
}
}
|
; A028158: Expansion of 1/((1-4x)(1-8x)(1-10x)(1-11x)).
; Submitted by Christian Krause
; 1,33,695,11925,181911,2572893,34540735,446515125,5610825671,68978848653,833511432975,9933242415525,117049255275031,1366477139586813,15829397675656415,182175233504671125,2085009104934341991,23750419100554859373,269443828297173915055
mov $1,1
mov $2,$0
mov $3,$0
lpb $2
mov $0,$3
sub $2,1
sub $0,$2
seq $0,19742 ; Expansion of 1/((1-4x)(1-10x)(1-11x)).
mul $1,8
add $1,$0
lpe
mov $0,$1
|
; A142231: Primes congruent to 34 mod 41.
; Submitted by Jamie Morken(s4)
; 157,239,977,1223,1879,2207,2371,2617,2699,3109,3191,3847,3929,4093,4339,4421,4831,5077,5323,5569,5651,5897,6143,6389,6553,7127,7537,8111,8521,8849,9013,9341,9587,9833,10079,10243,11719,11801,12211,12457,12539,12703,13441,13523,13687,13933,14753,15737,15901,16229,17377,17623,18443,19181,19427,19919,20411,20903,21067,21149,21313,21559,22051,22133,22543,22871,23117,23609,23773,24019,24593,25577,25741,26479,26561,27299,27791,28201,28283,28447,29021,29759,30169,30497,30661,31153,31481,31727,31891
mov $1,13
mov $2,$0
add $2,2
pow $2,2
lpb $2
add $1,24
mul $1,2
sub $2,1
mov $3,$1
add $1,3
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,31
div $1,2
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mov $0,$1
mul $0,2
sub $0,33
|
; A134467: a(n) = n(n+1) - A000120(n), where A000120(n) = number of 1's in binary expansion of n.
; 0,1,5,10,19,28,40,53,71,88,108,129,154,179,207,236,271,304,340,377,418,459,503,548,598,647,699,752,809,866,926,987,1055,1120,1188,1257,1330,1403,1479,1556,1638,1719,1803,1888,1977,2066,2158,2251,2350,2447,2547,2648,2753,2858,2966,3075,3189,3302,3418,3535,3656,3777,3901,4026,4159,4288,4420,4553,4690,4827,4967,5108,5254,5399,5547,5696,5849,6002,6158,6315,6478,6639,6803,6968,7137,7306,7478,7651,7829,8006,8186,8367,8552,8737,8925,9114,9310,9503,9699,9896,10097,10298,10502,10707,10917,11126,11338,11551,11768,11985,12205,12426,12653,12878,13106,13335,13568,13801,14037,14274,14516,14757,15001,15246,15495,15744,15996,16249,16511,16768,17028,17289,17554,17819,18087,18356,18630,18903,19179,19456,19737,20018,20302,20587,20878,21167,21459,21752,22049,22346,22646,22947,23253,23558,23866,24175,24488,24801,25117,25434,25758,26079,26403,26728,27057,27386,27718,28051,28389,28726,29066,29407,29752,30097,30445,30794,31149,31502,31858,32215,32576,32937,33301,33666,34036,34405,34777,35150,35527,35904,36284,36665,37054,37439,37827,38216,38609,39002,39398,39795,40197,40598,41002,41407,41816,42225,42637,43050,43469,43886,44306,44727,45152,45577,46005,46434,46868,47301,47737,48174,48615,49056,49500,49945,50397,50846,51298,51751,52208,52665,53125,53586,54052,54517,54985,55454,55927,56400,56876,57353,57836,58317,58801,59286,59775,60264,60756,61249,61747,62244
mov $1,$0
mul $1,$0
lpb $0
div $0,2
add $1,$0
lpe
|
; A053384: A053398(4, n).
; 2,2,2,2,3,3,3,3,2,2,2,2,4,4,4,4,2,2,2,2,3,3,3,3,2,2,2,2,5,5,5,5,2,2,2,2,3,3,3,3,2,2,2,2,4,4,4,4,2,2,2,2,3,3,3,3,2,2,2,2,6,6,6,6,2,2,2,2,3,3,3,3,2,2,2,2,4,4,4,4,2,2,2,2,3,3,3,3,2,2,2,2,5,5,5,5,2,2,2,2,3,3,3,3,2,2,2,2,4,4,4,4,2,2,2,2,3,3,3,3,2,2,2,2,7,7,7,7,2,2,2,2,3,3,3,3,2,2,2,2,4,4,4,4,2,2,2,2,3,3,3,3,2,2,2,2,5,5,5,5,2,2,2,2,3,3,3,3,2,2,2,2,4,4,4,4,2,2,2,2,3,3,3,3,2,2,2,2,6,6,6,6,2,2,2,2,3,3,3,3,2,2,2,2,4,4,4,4,2,2,2,2,3,3,3,3,2,2,2,2,5,5,5,5,2,2,2,2,3,3,3,3,2,2,2,2,4,4,4,4,2,2,2,2,3,3,3,3,2,2
div $0,2
add $0,2
mov $1,4
mov $2,2
lpb $0
div $0,$2
add $1,1
gcd $2,$0
lpe
sub $1,3
|
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# 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.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 5, 0x90
.globl g9_cpSub_BNU
.type g9_cpSub_BNU, @function
g9_cpSub_BNU:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
movl (12)(%ebp), %eax
movl (16)(%ebp), %ebx
movl (8)(%ebp), %edx
movl (20)(%ebp), %edi
shl $(2), %edi
xor %ecx, %ecx
pandn %mm0, %mm0
.p2align 5, 0x90
.Lmain_loopgas_1:
movd (%ecx,%eax), %mm1
movd (%ebx,%ecx), %mm2
paddq %mm1, %mm0
psubq %mm2, %mm0
movd %mm0, (%edx,%ecx)
pshufw $(254), %mm0, %mm0
add $(4), %ecx
cmp %edi, %ecx
jl .Lmain_loopgas_1
movd %mm0, %eax
neg %eax
emms
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.Lfe1:
.size g9_cpSub_BNU, .Lfe1-(g9_cpSub_BNU)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.