P4_16使用table实现通用的switch分支语句

本文介绍了如何在P4_16编程语言中,通过使用table的Match-Action机制和P4_16Table的switch语句,解决早期版本switch语句选择条件的限制,实现高效通用的switch结构,替代低效的if-else实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0 背景

v1.2.1 以及更早版本的P4_16编程语言中,尽管在Control中支持switch分支语句,但是switch中的选择条件是受限的,仅支持 table_name.apply().action_run 作为switch的选择条件。为了解决此限制,将尝试使用P4_16 Table+switch来实现一个通用的switch语句。

1 目标

使用P4中的table_name.apply().action_run实现如下伪代码

bit<16> x;

switch (x) {
   1: { /* body 1 here */ }
   2:
   3: { /* body 23 here */ }
   4: { /* body 4 here */ }
   default: { /* body D here */ }
}

2 使用if-else实现

if (x == 1) {
    /* body 1 here */
} else if ((x == 2) || (x == 3)) {
    /* body 23 here */
} else if (x == 4) {
    /* body 4 here */
} else {
    /* body D here */
}

这种实现方法逻辑没问题,功能实现没问题,但是效率极低。

3 使用table实现

原理:

使用table的Match-Action机制+P4_16中的switch语句来判断执行了哪个Action,进而判断具体是匹配到了table中的哪一项。

具体代码:


bit<16> x; //选择条件
//table中的Action 仅需声明即可,使用@hidden注解指示编译器该部分需要向控制面隐藏
@hidden action switch1_case_1 () {
    // no statements here, by design
}
@hidden action switch1_case_23 () {
    // no statements here, by design
}
@hidden action switch1_case_4 () {
    // no statements here, by design
}
@hidden action switch1_case_default () {
    // no statements here, by design
}

@hidden table switch1_table {
    key = {
        x : exact; //精确匹配
    }
    //table中的所有action
    actions = {
        switch1_case_1;
        switch1_case_23;
        switch1_case_4;
        switch1_case_default;
    }
    //table的表项。注:此处具体的表项并不是从控制面添加的,而是写进代码中编译。
    //主要是因为这个table对控制面是不可见的
    const entries = {
        1 : switch1_case_1;
        2 : switch1_case_23;
        3 : switch1_case_23;
        4 : switch1_case_4;
    }
    const default_action = switch1_case_default;
}

// later in the control's apply block, where the original switch
// statement appeared:
apply(){
		//根据执行table中执行了哪个action来确定match到哪一项
		switch (switch1_table.apply().action_run) {
			switch1_case_1:       { /* body 1 here */ }
			switch1_case_23:      { /* body 23 here */ }
			switch1_case_4:       { /* body 4 here */ }
			switch1_case_default: { /* body D here */ }
		}
}

使用table的Match-Action来实现的通用switch执行效率极高

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值