Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

68
LINES

< > BotCompany Repo | #1035284 // FixedVarContext - a VarContext with a fixed number of variables

JavaX fragment (include) [tags: use-pretranspiled]

Transpiled version (8439L) is out of date.

// Always thread-safe
sclass FixedVarContext > VarContext {
  S[] names; // always sorted, may be null
  O[] values; // same length as names, may also be null
  
  *() {}
  *(S[] *names) { this(null, names); }
  *(VarContext parent, S[] *names) {
    super(parent);
    if (names != null) values = new O[names.length];
  }
  
  int indexOfVar(S name) {
    ret indexOfInSortedArray(names, name);
  }
  
  int indexOfVarMandatory(S name) {
    int idx = indexOfVar(name);
    if (idx < 0) fail("Variable not found: " + name + ", known: " + joinWithComma(names));
    ret idx;
  }
  
  O get(int idx) {
    ret values[idx];
  }
  
  O get(S name) {
    int idx = indexOfVar(name);
    if (idx >= 0) ret values[idx];
    if (parent != null)
      ret parent.get(name);
    null;
  }
  
  void set(int idx, O value) {
    values[idx] = value;
  }
  
  void set(S name, O value) {
    int idx = indexOfVar(name);
    if (idx >= 0)
      values[idx] = value;
    else
      fail("Variable " + name + " not defined in context");
  }
  
  AutoCloseable tempSet(S name, O value) {
    int idx = indexOfVar(name);
    if (idx >= 0) {
      O old = values[idx];
      values[idx] = value;
      ret -> values[idx] = old;
    } else
      fail("Variable " + name + " not defined in context");
  }
  
  void unset(S name) {
    set(name, null);
  }
  
  MapSO varMap() {
    new MapSO map;
    int n = l(names);
    for i to n:
      map.put(names[i], values[i]);
    ret map;
  }
}

Author comment

Began life as a copy of #1033977

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035284
Snippet name: FixedVarContext - a VarContext with a fixed number of variables
Eternal ID of this version: #1035284/4
Text MD5: 0a34952a70be15bb30ce0922bd459212
Author: stefan
Category: javax / parsing
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-04-29 00:32:06
Source code size: 1536 bytes / 68 lines
Pitched / IR pitched: No / No
Views / Downloads: 122 / 198
Version history: 3 change(s)
Referenced in: #1003674 - Standard Classes + Interfaces (LIVE continued in #1034167)